Zod le JavaScript
Ar an leathanach seo
Aschuir struchtúrtha i JavaScript
Má tá tú ag forbairt i JavaScript nó TypeScript, is ionann Zod agus Pydantic. Comhtháthaíonn an leabharlann bailíochtaithe scéimre seo go réidh leis an API Grok chun aschuir struchtúrtha de chineál sonraithe a ghiniúint.
Suiteáil
npm install zod openai
Oibríonn SDK OpenAI do JavaScript go díreach leis an API Grok—níl le déanamh agat ach é a dhíriú ar an bpointe deiridh ceart.
Cumraíocht an chliaint
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "your-xai-key",
baseURL: "https://api.x.ai/v1"
});
Scéimre a shainiú le Zod
Úsáideann Zod API sreabhach chun scéimrí a shainiú. Mapálann gach modh go cineál JSON:
import { z } from "zod";
const MovieReview = z.object({
title: z.string(),
rating: z.number(),
summary: z.string(),
recommend: z.boolean()
});
Mapáil cineálacha
| Zod | Scéimre JSON | Pydantic (Python) |
|---|---|---|
z.string() | "type": "string" | str |
z.number() | "type": "number" | float |
z.boolean() | "type": "boolean" | bool |
z.array(z.string()) | array de shreangáin | list[str] |
z.object({...}) | "type": "object" | BaseModel |
z.enum([...]) | enum | Literal[...] |
z.union([...]) | anyOf | Cineálacha Aontais |
z.nullable() | anyOf le null | str | None |
Sampla iomlán
import OpenAI from "openai";
import { z } from "zod";
const client = new OpenAI({
apiKey: "your-xai-key",
baseURL: "https://api.x.ai/v1"
});
const Analyse = z.object({
titre: z.string(),
resume: z.string(),
sentiment: z.enum(["positif", "negatif", "neutre"]),
score: z.number(),
mots_cles: z.array(z.string()),
recommandation: z.boolean()
});
const response = await client.chat.completions.create({
model: "grok-4.20-0309-reasoning",
messages: [{
role: "user",
content: "Analyze the following text: Sales increased by 25% this quarter."
}],
response_format: {
type: "json_schema",
json_schema: {
name: "analyse",
schema: Analyse
}
}
});
const data = JSON.parse(response.choices[0].message.content);
console.log(data.sentiment); // "positive"
console.log(data.score); // 0.92
Scéimrí neadaithe
Cosúil le Pydantic, láimhseálann Zod neadú go nádúrtha:
const Adresse = z.object({
rue: z.string(),
ville: z.string(),
code_postal: z.string(),
pays: z.string()
});
const Contact = z.object({
nom: z.string(),
email: z.string(),
telephone: z.string().nullable(),
adresse: Adresse,
tags: z.array(z.string())
});
Réimsí roghnacha le nullable
Chun réimse a dhéanamh roghnach (in ann a bheith null), úsáid .nullable():
const Produit = z.object({
nom: z.string(),
prix: z.number(),
description: z.string().nullable(),
promotion: z.number().nullable()
});
Bailíochtú taobh an chliaint
Is buntáiste amháin de chuid Zod ná gur féidir leat sonraí a bhailíochtú ar thaobh an chliaint ag baint úsáide as an scéimre céanna:
const rawData = JSON.parse(response.choices[0].message.content);
// Bailíochtú le Zod
const result = Analyse.safeParse(rawData);
if (result.success) {
console.log(result.data.titre);
} else {
console.error("Earráid bailíochtaithe:", result.error);
}
Go praiticiúil, éireoidh leis an mbailíochtú i gcónaí toisc go ráthaíonn an API comhlíonadh an scéimre. Mar sin féin, tá an sraith bhreise seo úsáideach le haghaidh seasmhachta sa táirgeadh.
Príomhphointí
- Is ionann Zod do JavaScript/TypeScript agus Pydantic
- Tá an chomhréir sreabhach:
z.string(),z.number(),z.object({...}) - Déanann
.nullable()réimse roghnach (is féidir leis a bheithnull) - Cuir scéimrí Zod ar fáil i
response_format.json_schema.schema - Cumasaíonn
safeParse()bailíochtú cosantach taobh an chliaint - Oibríonn SDK OpenAI do JavaScript go díreach leis an API Grok