JavaScript检索并替换字符串化JSON中的字符串部分

JavaScript检索并替换字符串化JSON中的字符串部分

问题描述:

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

I have a string compared to this:

{
    "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的值,然后将它们乘以一个系数,然后再次将它们另存为新字符串.

I need to loop to this string and retrieve the values of left, top, width and height and multiply them by a factor and then save them as a new string again.

关于如何实现此目标的任何想法吗?

Any idea of how I could accomplish this?

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

Because the string is JSON, the easiest way to handle the data is to parse it into an array of objects, update the values, then output it as a string again.

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