mynameisnotallowed
mynameisnotallowed

Reputation: 483

modify value of JSON obj with known location in javascript

In a JSON file of unknown complexity I need to modify a specific value of which I have the location.

If this is my JSON:

{
    "first": {
        "beans": [{
            "joystick": {}
        }, {
            "adolf": {
                "dolphin": "this has to change"
            }
        }]
    },
    "second": {}
}

How do I change the value at this location of str:

var str = 'root["first"]["beans"][1]["adolf"]["dolphin"]'

Upvotes: 1

Views: 73

Answers (3)

nnnnnn
nnnnnn

Reputation: 150080

Assuming you've parsed your JSON you can do something like this:

function changeProperty(obj, strProp, newValue) {
    var re = /\["?([^"\]]+)"?\]/g,
        m, 
        p,
        o = obj;
    while ((m = re.exec(strProp)) && typeof o[p = m[1]] === "object")
        o = o[p];

    if (p)
        o[p] = newValue;
}

changeProperty(root, str, "Some new value");

Demo: http://jsfiddle.net/D6ECW/

Or if using eval() is acceptable you can do this:

eval(str + ' = "Some new value"');

Demo: http://jsfiddle.net/D6ECW/1/

Note that both ways assume the chain specified in str actually exists.

Upvotes: 3

Prateek
Prateek

Reputation: 6975

You can use jQuery.parseJSON

jQuery.parseJSON(str);

Upvotes: 0

gauravmuk
gauravmuk

Reputation: 1616

This should solve it

var variable = {
    "first": {
        "beans": [{
            "joystick": {}
        }, {
            "adolf": {
                "dolphin": "this has to change"
            }
        }]
    },
    "second": {}
}

alert("Before: " + variable.first.beans[1].adolf.dolphin);

variable.first.beans[1].adolf.dolphin = "my new string";

alert("After: " + variable.first.beans[1].adolf.dolphin);

Fiddle

Upvotes: 1

Related Questions