agentpx
agentpx

Reputation: 1081

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

Given a browser debugger output of root.value with two properties in javascript

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

I want to parse it to a JSON string including the type like below

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

Does any one know how to do that in javascript or any framework I can use to achieve such?

Note: I did not created the JSON myself it's an output of another framework. So the types of the fields are unknown until runtime.

 JSON.stringify(root.value);

with only return

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

Upvotes: 2

Views: 2150

Answers (2)

You can also use the following function.

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
    };
  }
}

You can invoke it as below

getSchema('My object', myObj)

Upvotes: 5

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

You can itertate through the object properties and combine the required object.

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>");

Note that the most outer braces are [] because the expected result is an array of objects. The JSON that you have provided in your question is invalid as long as your objects have no name.

Also, note that this script will not process inner objects recursively - you can do this yourself.

Upvotes: 1

Related Questions