Giovanni Fiore Giovanni Fiore - 3 months ago 8
Javascript Question

Create a JSON reading recursively from another unknown JSON with Javascript

I'd like to read recursively all nodes from a generic JSON (so I'm not asking for a script that handles exclusively this kind of structure) and while reading I would to create another JSON in a structure like this (the example is just an excerpt):

[
{
"name":"AgreementOffer",
"size":20000000,
"children":[
{
"name":"Name",
"size":2000000,
"children":[
{
"name":"1cap",
"size":90
}
]
},
{
"name":"Context",
"size":2000000,
"children":[
{
"name":"AgreementInitiator",
"size":200,
"children":[
{
"name":"$SPECS-CUSTOMER",
"size":100
}
]
},
{
"name":"AgreementInitiator",
"size":200,
"children":[
{
"name":"$SPECS-CUSTOMER",
"size":100
}
]
},
{
"name":"AgreementResponder",
"size":200,
"children":[
{
"name":"$SPECS-APPLICATION",
"size":100
}
]
},
{
"name":"AgreementResponder",
"size":200,
"children":[
{
"name":"$SPECS-APPLICATION",
"size":100
}
]
},
{
"name":"ServiceProvider",
"size":200,
"children":[
{
"name":"AgreementResponder",
"size":100
}
]
},
{
"name":"ServiceProvider",
"size":200,
"children":[
{
"name":"AgreementResponder",
"size":100
}
]
},
{
"name":"ExpirationTime",
"size":200,
"children":[
{
"name":"2014-02-02T06:00:00",
"size":100
}
]
},
{
"name":"ExpirationTime",
"size":200,
"children":[
{
"name":"2014-02-02T06:00:00",
"size":100
}
]
},
{
"name":"TemplateName",
"size":200,
"children":[
{
"name":"Y2-APP-TEMPLATE",
"size":100
}
]
},
{
"name":"TemplateName",
"size":200,
"children":[
{
"name":"Y2-APP-TEMPLATE",
"size":100
}
]
}
]
}
]
}
]


So, I ask you for a script be able to handle a generic JSON (unknown structure and deep) and create another JSON written with the above structure.

Thanks!

Answer

Try it at https://jsfiddle.net/zqkdq5mf/1/

function AppendObject(obj) {
    //console.log(JSON.stringify(obj) + ":" + JSON.stringify(obj).length);

    var Summary = null;
    for (var propertyName in obj) {
    if (typeof obj[propertyName] === "object" && !Summary) {
        Summary = { name: propertyName.toString(), size: JSON.stringify(obj).length, children: [] };

      for (var childPropertyName in obj[propertyName]) {
        var Child = {};
        Child[childPropertyName] = obj[propertyName][childPropertyName];
        Summary.children[Summary.children.length] = AppendObject(Child);
      }
      break;
    } else if (!Summary) Summary = { key: propertyName, value: obj[propertyName], size: JSON.stringify(obj).length };
  }

  return Summary;
}

function Convert() {
    $(".data").empty();
    var ParsedJSON = $.parseJSON($("textarea").val()),
        ObjectArray = [],
        Summaries = [];

    if (!(ParsedJSON instanceof Array)) ObjectArray[0] = ParsedJSON;
    else ObjectArray = ParsedJSON;

    for (var i = 0; i < ObjectArray.length; i++) Summaries[Summaries.length] = AppendObject(ObjectArray[i]);

    $(".data").text(JSON.stringify(Summaries));
}
Comments