Samplaí Práctacha de Mhód JSON
Ar an leathanach seo
Nuashonraithe an 3 Samhain 2026: D’iompórtáil an sampla TypeScript
Mistralmar easpórtáil réamhshocraithe roimhe seo, ach ní sholáthraíonn an SDK ach easpórtáil ainmnithe (import { Mistral } from "@mistralai/mistralai"). Chuaigh sé i muinín eochair API a bheith crua-chódaithe agus chuir sé cineálcontenti bhfeidhm go héignitheach le!, rud nach leor toisc gur féidir leis an réimse a bheith ina liosta smutání freisin. Fíoraithe trí thiomsú le SDK 3.5.0 agus TypeScript 7.0.2. Foinse: Mistral TypeScript SDK.
Mód JSON a chur i bhfeidhm sa chleachtas
Tá a fhios agat conas Mód JSON a chumasú; anois, déanaimis breathnú ar shamplaí oibre. Tagann trí chás chun cinn go minic i dtionscadail fhíorshaol, agus léiríonn gach ceann acu bealach difriúil chun leas a bhaint as an mód. Soláthraítear an cód i bPython, le leaganacha coibhéiseacha i TypeScript nuair nach bhfuil an t-aistriú láithreach.
Aonáin a eastóscadh ó théacs neamhstruchtúrtha
Is é eastóscadh aonán an cás úsáide is minice agus is cost-éifeachtaí: tá sonraí teagmhála iomlána i ríomhphost díolacháin, ach tá siad faoi cheilt i síniú agus i gcúirtéis. Is í an treoir lárnach sa sampla seo ná an líne dheireanach den leid córais – éilíonn sé null le haghaidh faisnéis atá ar iarraidh, rud a chuireann cosc ar an tsamhail uimhir theileafóin a cheapadh díreach chun an réimse a líonadh.
from mistralai.client import Mistral
import json
client = Mistral(api_key="your-api-key")
email_text = """
Hello,
I am Marie Dupont, Sales Director at TechVision SAS.
You can reach me at 06 12 34 56 78 or by email at [email protected].
Our headquarters are at 42 rue de la Paix, 75002 Paris.
Best regards,
Marie
"""
response = client.chat.complete(
model="mistral-large-latest",
messages=[
{
"role": "system",
"content": """Extract contact information from the provided text.
Return a JSON with keys: name, title, company, phone, email, address.
If information is missing, use null."""
},
{"role": "user", "content": email_text}
],
response_format={"type": "json_object"},
temperature=0
)
contact = json.loads(response.choices[0].message.content)
print(f"Name: {contact['name']}")
print(f"Company: {contact['company']}")
print(f"Phone: {contact['phone']}")
Aschur expected:
{
"name": "Marie Dupont",
"title": "Sales Director",
"company": "TechVision SAS",
"phone": "06 12 34 56 78",
"email": "[email protected]",
"address": "42 rue de la Paix, 75002 Paris"
}
Ticéid Tacaíochta a Aicmiú
Éilíonn aicmiú cur chuige difriúil: in ionad ligean don tsamhail a luachanna féin a roghnú, déanann tú liosta de na luachanna ceadaithe do gach réimse sa leid. Déanann sé seo torthaí inchomparáide ó thicéad go ticéad agus inúsáidte go díreach le haghaidh ródaíochta. Tabhair faoi deara an t-aistriú go mistral-small-latest – ní gá an tsamhail is cumhachtaí a úsáid le haghaidh sórtáil ticéad.
tickets = [
"My payment was charged twice, I demand an immediate refund!",
"How can I change my password?",
"Your app crashes every time I open the settings tab.",
]
for ticket in tickets:
response = client.chat.complete(
model="mistral-small-latest",
messages=[
{
"role": "system",
"content": """Classify the support ticket.
Return a JSON with:
- category: "billing", "account", "technical", "feature_request", or "other"
- priority: "low", "medium", "high", or "critical"
- sentiment: "positive", "neutral", or "negative"
- summary: one-sentence summary"""
},
{"role": "user", "content": ticket}
],
response_format={"type": "json_object"},
temperature=0
)
result = json.loads(response.choices[0].message.content)
print(f"Category: {result['category']} | Priority: {result['priority']} | Sentiment: {result['sentiment']}")
Seo an t-aicmitheoir céanna i TypeScript. Cuireann an seiceáil roimh JSON.parse i gcuimhne dúinn go ndéanann na cineálacha SDK content a chineálú mar roghnach agus mar string | ContentChunk[]: ní féidir ach teaghrán a pharsáil.
import { Mistral } from "@mistralai/mistralai";
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
const ticket = "My payment was charged twice!";
const response = await client.chat.complete({
model: "mistral-small-latest",
messages: [
{
role: "system",
content: `Classify the support ticket.
Return a JSON with: category, priority, sentiment, summary.`,
},
{ role: "user", content: ticket },
],
responseFormat: { type: "json_object" },
temperature: 0,
});
const contenu = response.choices[0]?.message?.content;
if (typeof contenu !== "string") {
throw new Error("The response does not contain JSON text.");
}
const result = JSON.parse(contenu);
console.log(`Category: ${result.category}`);
console.log(`Priority: ${result.priority}`);
Cur síos a thiontú ina Bileog Táirge
An tríú cás: téacs margaíochta a chlaochlú ina thaifead atá réidh le haghaidh bunachair sonraí. Is cleachtas níos deacra é seo toisc go bhfuil tábhacht le cineálacha – caithfidh praghas teacht mar uimhir, fad seachadta mar dhá shlánuimhir, agus seachadadh saor in aisce mar bhooleán. Mar sin, tá na nótaí beachta sa leid.
product_text = """
The 16-inch MacBook Pro with M4 Pro chip is available starting at €2,799.
It features 24 GB of unified RAM, a 512 GB SSD, and a Liquid Retina XDR display.
Available in Space Black and Silver. Free delivery within 3-5 days.
"""
response = client.chat.complete(
model="mistral-large-latest",
messages=[
{
"role": "system",
"content": """Convert the product description into a structured sheet.
JSON with: name, brand, price_eur (number), specs (object with ram_gb, storage_gb, screen),
colors (list), delivery_days_min, delivery_days_max, free_shipping (boolean)."""
},
{"role": "user", "content": product_text}
],
response_format={"type": "json_object"},
temperature=0
)
product = json.loads(response.choices[0].message.content)
print(json.dumps(product, indent=2, ensure_ascii=False))
Toradh:
{
"name": "MacBook Pro 16-inch",
"brand": "Apple",
"price_eur": 2799,
"specs": {
"ram_gb": 24,
"storage_gb": 512,
"screen": "Liquid Retina XDR"
},
"colors": ["Space Black", "Silver"],
"delivery_days_min": 3,
"delivery_days_max": 5,
"free_shipping": true
}
Tabhair faoi deara nach bhfuil an branda, Apple, le feiceáil in aon áit sa téacs foinseach: rinne an tsamhail é a thátal ó ainm an táirge. Is neart é seo le haghaidh saibhrithe, ach is riosca é le monatóireacht a dhéanamh air má éilíonn tú eastóscadh liteartha go hiomlán.
Míreanna Iolracha a Phróiseáil in Aon Ghla Amháin
Níl aon rud a chuireann iallach ort gla amháin a dhéanamh in aghaidh na míre. Trí iarraidh ar an tsamhail liosta faoi eochair amháin, laghdaíonn tú líon na n-iarratas – agus mar sin an moill charnaigh – do thascanna gairide cosúil le hanailís athbhreithnithe. Raonann an scór a iarrtar anseo ó -1.0 go 1.0, comhghnáthú úsáideach chun torthaí a chomhiomlánú níos déanaí.
texts = [
"Excellent product, I recommend it!",
"Late delivery, damaged product.",
"Decent for the price, nothing exceptional."
]
response = client.chat.complete(
model="mistral-small-latest",
messages=[
{
"role": "system",
"content": "Analyze the sentiment of each review. Return a JSON with a key 'reviews' containing a list of objects {text, sentiment, score}. The score ranges from -1.0 (very negative) to 1.0 (very positive)."
},
{"role": "user", "content": "\n---\n".join(texts)}
],
response_format={"type": "json_object"},
temperature=0
)
reviews = json.loads(response.choices[0].message.content)["reviews"]
for r in reviews:
print(f"[{r['score']:+.1f}] {r['sentiment']} — {r['text'][:40]}...")
Is fiú béim a chur ar mhionsonra amháin atá coiteann do na samplaí seo go léir: tá temperature=0 córasach anseo. Do thascanna eastósctha agus aicmithe, ní chuireann cruthaitheacht aon rud leis agus cosnaíonn sé in-atáirgeadh.
Príomhphointí
- Buaileann Mód JSON spriocanna maidir le hastóscadh sonraí, aicmiú agus tiontú
- Úsáid an leid córais chun an struchtúr agus na cineálacha ionchais a shainiú
- Cinntíonn
temperature=0torthaí in-atáirgthe - Is féidir próiseáil bhaisce in aon iarratas amháin trí liosta JSON a iarraidh
- Parsáil an freagra i gcónaí le
json.loads()/JSON.parse()sula ndéanann tú rochtain ar na sonraí