Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to JSONPath

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?

like image 532
CodyBugstein Avatar asked Apr 21 '26 15:04

CodyBugstein


2 Answers

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.

like image 198
Georgios Syngouroglou Avatar answered Apr 24 '26 04:04

Georgios Syngouroglou


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
like image 28
Joe Thomas Avatar answered Apr 24 '26 05:04

Joe Thomas