0

I have performed diff of two json files with the output being an array of strings indicating the location within a json tree.

The original json file is something along the lines of:

{
  'key': {
    'key3': 'value'
  },
  'key1': {
    'key2': 'value2'
  }
  'key5': {
    'key4': 'value4'
  }
}

And the output of the diff is:

[
  'key.key3',
  'key1.key2'
]

I'm able to cycle through all the strings in the array:

(difference).forEach((k) => {
  console.log(k);
})

How do I access the value from the original json file using the strings set by the forEach() function above? I want something like what would be returned if I called originalJSON.key1.key2 directly, but it has to be made up by the strings in the above function.

I've tried originalJSON[k] but that just returns undefined.

oldo.nicho
  • 2,149
  • 2
  • 25
  • 39
  • 2
    [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – Andreas Jun 20 '17 at 15:13
  • That's not valid JSON. JSON requires double quotes. – PeterMader Jun 20 '17 at 15:14
  • Ok, thanks, yes you're right. Should have double quotes and seems I'm misled with the terminology of JSON objects. The suggested 'possible duplicate' should resolve the issue. Thanks @Andreas – oldo.nicho Jun 20 '17 at 15:17

1 Answers1

3

You have to split 'key.key3' into 'key' and 'key3'.

One way to do this is just to 'key.key3'.split(".") which gives ['key','key3']

Then you can use them to navigate through your original object :

(difference).forEach( k => {
  var keys = k.split(".")         // ['key','key3']
  var val = originalJSON[keys[0]][keys[1]] // == originalJSON['key']['key3']
  console.log(val);                        // 'value', 'value2', 'value4'
})
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63