3

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?

0

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I feel like there must be a better way to do this
1

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

1 Comment

The only problem with this is that it gives me the value of the object but not the reference. I can't update the object with p
0

I came up with a way to get it to work. It doesn't seem "right" but it's still an answer. (I will mark as accepted any answer better than this)

for (var key in currentObject){
       delete currentObject[key];
}

This clears out the Yukon object.

Updated fiddle: http://jsfiddle.net/ay1wpr5L/3/

1 Comment

That's not answering the question you asked though...
0

You can use eval function of javascript to evaluate the final result, Solution would look something like this

let countriesObj = {<your json object>}
let path = "countries.canada.territories.yukon";
let properties = path.split(".");
let propertyStr = "";
for(let property in properties){
    propertyStr+="['"+properties[property]+"']"
}

let result = undefined;
let expression = "result = countriesObj"+propertyStr+";";
eval(expression);
return result;

this will give you the exact result

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.