JSON转TypeScript

将JSON转换为TypeScript代码
JSON转TypeScript
 
仅使用接口
 
将属性名转为JavaScript风格
 
显式命名联合类型
 
运行时验证JSON.parse结果
 
使用联合类型代替枚举
 
使用类型代替接口
 
对单值枚举使用字符串代替枚举
 
使用只读类型成员
 
所有属性可选
您的TypeScript代码
// To parse this data://// import { Convert, MyType } from "./file";//// const myType = Convert.toMyType(json);//// These functions will throw an error if the JSON doesn't// match the expected interface, even if the JSON is valid.exportinterfaceMyType { a: string; arr: number[]; nested: Nested; } exportinterfaceNested { a: number; b: string; } // Converts JSON strings to/from your types// and asserts the results of JSON.parse at runtimeexportclassConvert { publicstatictoMyType(json: string): MyType { returncast(JSON.parse(json), r("MyType")); } publicstaticmyTypeToJson(value: MyType): string { returnJSON.stringify(uncast(value, r("MyType")), null, 2); } } functioninvalidValue(typ: any, val: any, key: any, parent: any = ''): never { const prettyTyp = prettyTypeName(typ); const parentText = parent ? ` on ${parent}` : ''; const keyText = key ? ` for key "${key}"` : ''; throwError(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`); } functionprettyTypeName(typ: any): string { if (Array.isArray(typ)) { if (typ.length === 2 && typ[0] === undefined) { return`an optional ${prettyTypeName(typ[1])}`; } else { return`one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`; } } elseif (typeof typ === "object" && typ.literal !== undefined) { return typ.literal; } else { returntypeof typ; } } functionjsonToJSProps(typ: any): any { if (typ.jsonToJS === undefined) { constmap: any = {}; typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ }); typ.jsonToJS = map; } return typ.jsonToJS; } functionjsToJSONProps(typ: any): any { if (typ.jsToJSON === undefined) { constmap: any = {}; typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ }); typ.jsToJSON = map; } return typ.jsToJSON; } functiontransform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any { functiontransformPrimitive(typ: string, val: any): any { if (typeof typ === typeof val) return val; returninvalidValue(typ, val, key, parent); } functiontransformUnion(typs: any[], val: any): any { // val must validate against one typ in typsconst l = typs.length; for (let i = 0; i < l; i++) { const typ = typs[i]; try { returntransform(val, typ, getProps); } catch (_) {} } returninvalidValue(typs, val, key, parent); } functiontransformEnum(cases: string[], val: any): any { if (cases.indexOf(val) !== -1) return val; returninvalidValue(cases.map(a => { returnl(a); }), val, key, parent); } functiontransformArray(typ: any, val: any): any { // val must be an array with no invalid elementsif (!Array.isArray(val)) returninvalidValue(l("array"), val, key, parent); return val.map(el =>transform(el, typ, getProps)); } functiontransformDate(val: any): any { if (val === null) { returnnull; } const d = newDate(val); if (isNaN(d.valueOf())) { returninvalidValue(l("Date"), val, key, parent); } return d; } functiontransformObject(props: { [k: string]: any }, additional: any, val: any): any { if (val === null || typeof val !== "object" || Array.isArray(val)) { returninvalidValue(l(ref || "object"), val, key, parent); } constresult: any = {}; Object.getOwnPropertyNames(props).forEach(key => { const prop = props[key]; const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; result[prop.key] = transform(v, prop.typ, getProps, key, ref); }); Object.getOwnPropertyNames(val).forEach(key => { if (!Object.prototype.hasOwnProperty.call(props, key)) { result[key] = transform(val[key], additional, getProps, key, ref); } }); return result; } if (typ === "any") return val; if (typ === null) { if (val === null) return val; returninvalidValue(typ, val, key, parent); } if (typ === false) returninvalidValue(typ, val, key, parent); letref: any = undefined; while (typeof typ === "object" && typ.ref !== undefined) { ref = typ.ref; typ = typeMap[typ.ref]; } if (Array.isArray(typ)) returntransformEnum(typ, val); if (typeof typ === "object") { return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) : invalidValue(typ, val, key, parent); } // Numbers can be parsed by Date but shouldn't be.if (typ === Date && typeof val !== "number") returntransformDate(val); returntransformPrimitive(typ, val); } function cast<T>(val: any, typ: any): T { returntransform(val, typ, jsonToJSProps); } function uncast<T>(val: T, typ: any): any { returntransform(val, typ, jsToJSONProps); } functionl(typ: any) { return { literal: typ }; } functiona(typ: any) { return { arrayItems: typ }; } functionu(...typs: any[]) { return { unionMembers: typs }; } functiono(props: any[], additional: any) { return { props, additional }; } functionm(additional: any) { return { props: [], additional }; } functionr(name: string) { return { ref: name }; } consttypeMap: any = { "MyType": o([ { json: "a", js: "a", typ: "" }, { json: "arr", js: "arr", typ: a(0) }, { json: "nested", js: "nested", typ: r("Nested") }, ], false), "Nested": o([ { json: "a", js: "a", typ: 0 }, { json: "b", js: "b", typ: "" }, ], false), }; 

相关工具 (20)

CSV转数据
将CSV文件转换为JSON、YAML、CSV、SQL INSERT、XML或Markdown
Excel转数据
将XLSX文件转换为JSON、YAML、CSV、SQL INSERT、XML或Markdown
JWT生成器
JWT令牌生成器和编辑器
JWT解析器
解析和解码您的JSON Web令牌(JWT)并显示其内容。
JSON 转卡通
将 JSON 对象转换为 LLM/GPT 使用的 TOON 表示形式
TOON 转 JSON
将 TOON 表示形式转换为 JSON 对象以供 LLM 使用
数据伪造工具
使用JSON模板生成假数据
文件分割器
将 JSON、XML 或文本文件按节点组或行组拆分。
JSON转Protobuf
从JSON对象生成Protobuf声明
JSON转SQL INSERT
将JSON数组转换为INSERT INTO语句
JSON转TypeScript
将JSON转换为TypeScript代码
CSV转JSON
自动检测表头,将CSV转换为JSON。
JS转JSON转换器
使用此在线工具直接将JavaScript对象转换为JSON。
JQ/JSONPath测试器
针对JSON内容测试jq/JSONPath表达式
JSON差异比较
比较两个JSON对象并获取它们之间的差异。
JSON编辑器
编辑JSON内容
JSON转义器/反转义器
转义和反转义JSON字符串
JSON展开/嵌套化工具
展开或嵌套化JSON内容(例如{a:{b:1}}与{"a.b":1})
JSON检查器
检查和清理JSON内容
JSON合并器
深度合并两个JSON内容
留言区
昵称
邮箱
网址
0/500
0 条评论
没有评论
查看更多
Powered by Twikoo v1.6.44
Twikoo 评论管理
密码