JavaScript检索并替换字符串化JSON中的字符串部分 [英] JavaScript retrieve and replace string parts in stringified JSON

查看:141
本文介绍了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);

这篇关于JavaScript检索并替换字符串化JSON中的字符串部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆