JavaScript以字符串化的JSON检索和替换字符串部分

时间:2014-05-12 13:38:03

标签: javascript json string replace

我有一个字符串与此相比:

{
    "objects": [{
        "originY": "top",
        "left": 0,
        "top": 0,
        "width": 118.33,
        "height": 100,
        "name": 1
    }, {
        "originY": "top",
        "left": 0,
        "top": 0,
        "width": 118.33,
        "height": 100,
        "name": 2
    }],
    "background": ""
}

我需要循环到此字符串并检索left,top,width和height的值,并将它们乘以一个因子,然后再将它们另存为新字符串。

我知道如何才能做到这一点?

2 个答案:

答案 0 :(得分:2)

因为字符串是JSON,处理数据的最简单方法是将其解析为对象数组,更新值,然后再将其作为字符串输出。

// Parse
var container = JSON.parse(yourString);

// Get and update
var i, len, top, left, width, height;
len = container.objects.length;
for (i = 0; i < len; i++) {
    top = container.objects[i].top;
    left = container.objects[i].left;
    height= container.objects[i].height;
    width = container.objects[i].width;
    // * Save top, left, width somewhere. *
    // Multiply by some factor.
    container.objects[i].top *= factor;
    container.objects[i].left *= factor;
    container.objects[i].height *= factor;
    container.objects[i].width *= factor;
}

// Convert to string again.
theString = JSON.stringify(container);

答案 1 :(得分:1)

您可以将json分配给变量,然后迭代它并执行您想要的任何操作

        var koko = {
            "objects": [{
                "originY": "top",
                "left": 1,
                "top": 0,
                "width": 118.33,
                "height": 100,
                "name": 1
            }, {
                "originY": "top",
                "left": 2,
                "top": 0,
                "width": 118.33,
                "height": 100,
                "name": 2
            }],
            "background": ""
        }



        for(var i=0;i<koko.objects.length;i++) { koko.objects[i].left = 10; }