agentpx agentpx - 1 year ago 83
JSON Question

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

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

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

"$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.


with only return

"firstname":" my name"
"age": 25

Answer Source

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download