使用javascript中的已知位置修改JSON obj的值

时间:2014-01-24 11:39:46

标签: javascript jquery json

在未知复杂度的JSON文件中,我需要修改具有该位置的特定值。

如果这是我的JSON:

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

如何更改str的此位置的值:

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

3 个答案:

答案 0 :(得分:3)

假设您已经解析了JSON,您可以执行以下操作:

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");

演示:http://jsfiddle.net/D6ECW/

或者如果使用eval()是可以接受的,您可以这样做:

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

演示:http://jsfiddle.net/D6ECW/1/

请注意,两种方式都假设str中指定的链实际存在。

答案 1 :(得分:1)

这应该解决它

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

答案 2 :(得分:0)

您可以使用jQuery.parseJSON

jQuery.parseJSON(str);