0

I receive a json from an API that I need to parse and modify one property value. Thing is, the nesting structure of the json data I receive are inconsistent and I have no control over it.

This will prohibit me to specify to look under a certain depth like parsedJson.children[0].property since the property I'm looking for could be found on a different nesting level like parsedJson.children[0].children[0].property on the next iteration.

I currently do it like this, and it works

var parsedJson = JSON.parse('{"a":[{"a1":[{"p":0},{"np":1}]}],"b":[{"p":0},{"np":1}],"c":[{"c1":[{"c2":[{"p":0}]},{"np":1}]}]}')


console.log("before modify")
console.log(parsedJson)

modifyProperty(parsedJson,"p",1);


function modifyProperty(obj,prop,val){
    for (var key in obj){
            if (key == prop){
            obj[key] = val;
        }
        modifyProperty(obj[key],prop,val);
    }
}

console.log("after modify")
console.log(parsedJson)

but I'm afraid later on, if I received a json from API that contains a lot more data and far deeper nesting levels that it may affect performance since this would need to recursively check all children nodes one by one.

Is there a better / faster way to this?

pokken
  • 327
  • 1
  • 15
  • So, your concern, I believe, is around the for loop ? And, not JSON parse ... Is that right ? – trk Mar 04 '19 at 02:47

1 Answers1

2

You can pass a second parameter to JSON.parse that recursively transforms all desired property values:

var parsedJson = JSON.parse(
  '{"a":[{"a1":[{"p":0},{"np":1}]}],"b":[{"p":0},{"np":1}],"c":[{"c1":[{"c2":[{"p":0}]},{"np":1}]}]}',
  (key, val) => key === 'p' ? 1 : val
);
console.log(parsedJson);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320