I have a JSON object that has a few nested levels in it.
I am given a string that refers to the location of a specific object.
For instance, if my JSON object looked like:
countries: [
canada: {
capital: "ottawa",
territories: [
yukon: {
capital: "yellowknife",
...
}
...
]
...
}
and I'm given the string
"countries.canada.territories.yukon"
I want to get the object for Yukon.
How can I do this?
I use this,
function jsonPathToValue(jsonData, path) {
if (!(jsonData instanceof Object) || typeof (path) === "undefined") {
throw "InvalidArgumentException(jsonData:" + jsonData + ", path:" + path);
}
path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
path = path.replace(/^\./, ''); // strip a leading dot
var pathArray = path.split('.');
for (var i = 0, n = pathArray.length; i < n; ++i) {
var key = pathArray[i];
if (key in jsonData) {
if (jsonData[key] !== null) {
jsonData = jsonData[key];
} else {
return null;
}
} else {
return key;
}
}
return jsonData;
}
A test,
json = {"a1":{"a2":{"a3":"value"}}};
console.log(jsonPathToValue(json, "a1.a2.a3")); //=> shows: value
Inspired from here.
Probably not the most effecient way, but it works.
var n= {JSON};
var c="countries.canada.territories.yukon".split('.');
var p=n;
for(var i=0;i<c.length;i++){
p=p[c[i]];
}
console.log(p);// p is your Yukon Element
if you want to edit the element use the eval function:
var myJSON= {JSON};
var c="countries.canada.territories.yukon";
c='myJSON["'+c+'"]';
c.replace(/\./g,'"]["');
eval(c+'={COOL_JSON_CODE}')
console.log(myJSON);// the Yukon element has cool new json code in it now
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With