如何获取JSON对象的模式并输出到包含类型的字符串

How to get the schema of a JSON object and output to string including types

本文关键字:模式 输出 包含 字符串 类型 对象 何获取 获取 JSON      更新时间:2023-09-26

给出了浏览器调试器的根输出。javascript中的两个属性值

root.value
__proto__: {...}
firstname: "my name"
age: 25

我想将其解析为JSON字符串,包括以下类型

{
  "$schema": "http://json-schema.org/draft-04/schema",
  "title": "Basic Info",
  "type": "object",
  "properties": {
       "firstName": {
           "type": "string"
         },
         "age": {
           "type": "number"
     }
   }
 }

有没有人知道如何在javascript或任何框架中做到这一点,我可以用它来实现这样的?

注意:JSON不是我自己创建的,它是另一个框架的输出。因此,在运行时之前,字段的类型是未知的。

 JSON.stringify(root.value);

只返回

{
   {
       "firstname":" my name"
   },
   {
        "age": 25
   }   
 }

您还可以使用以下函数。

function getSchema(id, obj) {
  if (Array.isArray(obj)) {
    var  retObj = getSchema(id, obj[0]);
    delete retObj.title;
    return {
      'title': id,
      'type': 'array',
      'items': retObj
    };
  } else if (typeof obj === 'object') {
    var retObj = {
      'title': id,
      'type': 'object'
    };
    retObj.properties = {};
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        retObj.properties[prop] = getSchema(prop, obj[prop]);
        delete retObj.properties[prop].title;
      }
    }
    return retObj;
  } else {
    return {
      'title': id,
      'type': typeof obj
    };
  }
}

你可以像下面这样调用它

getSchema('My object', myObj)

您可以遍历对象属性并组合所需的对象。

var o = { 
  d: 15,
  s: "qwe",
  b: true,
  q: {}
};
var result = [];
for (var property in o)
{
    if (!o.hasOwnProperty(property)) continue;
  
    var resultItem = {
        type: typeof(o[property])
    };
    resultItem[property] = o[property];
          
    result.push(resultItem);
}
var textResult = JSON.stringify(result, null, 2); // That's what you are looking for
document.write("<pre>" + textResult + "</pre>");

注意,最外层的花括号是[],因为预期的结果是对象的数组。只要您的对象没有名称,您在问题中提供的JSON就无效。

还要注意的是,这个脚本不会递归地处理内部对象——你可以自己做。