How do you get JSONPath for all child nodes in an array of JSON object?

How do you get JSONPath for the whole child node object?

eg:.

var data = [{ "key1": { "children": [{ "key2": "value", "key3": "value", "key4": {} }, { "key2": "value", "key3": "value", "key4": {} }], "key5": "value" } }, { "key1": { "children": { "key2": "value", "key3": "value", "key4": {} }, "key5": "value" } }] 

I want to get the absolute path for all nodes in the data structure as an array:

 [ "data[0]['key1']['children'][0]['key2']", "data[0]['key1']['children'][0]['key3']", "data[0]['key1']['children'][0]['key4']", ......, "data[0]['key1']['children'][1]['key2']", ......., "data[1]['key1']['children']['key2']", .......... ] 

Is there any way to do this in JS?

+4
source share
2 answers

I wrote a special code that gives us the JSON path for all nodes as an array

 function toArray(obj, name) { var result = []; var passName; var tempArray = []; for (var prop in obj) { var value = obj[prop]; if (typeof value === 'object') { if ($.isNumeric(prop)) { passName = name + "[" + prop + "]"; } else { passName = name + "['" + prop + "']"; } tempArray = toArray(value, passName); $.each(tempArray, function (key, value) { result.push(value); }); } else { result.push(name + "['" + prop + "']"); } } return result; } 

Js fiddle

+5
source

well, I think you need to go through your entire json structure.

  for(var i=0; i<data.length; i++) { for(var j in data[i]){ //and so on } } 

Or simply you can create an aleas arrary for each key, where the key will be the road of this value using "_" as a delimiter, like ..

  var aleasArray = []; for(var i=0; i<data.length; i++) { for(var j in data[i]){ aleasArray[i + '_' + j] = data[i][j]; // if you want make it more generalize aleas array.. } } 

Hope this helps you.

+2
source

Source: https://habr.com/ru/post/1500660/


All Articles