将值转换为json/object并更新条目

Convert value to json/object and update entry

本文关键字:更新 object 转换 json      更新时间:2023-09-26

我有下面的值"类似字符串",我想更新里面的一些值,我该怎么做?

这就是我在调试器中看到的

 var aa =   "'[{key:10,key2:20}]''r"

我需要将key的值更改为5,我该怎么做(假设我有更多的key(。

我尝试使用JSON.parse(aa),但我得到了错误

我也尝试使用aa[0].key = 5;也不起作用,

知道如何克服这个问题吗?

不能使用'r进行解析,因为它不是有效的json字符串。首先替换它,然后尝试解析(注意密钥与"一起(:

 var aa =   '[{"key":10,"key2":20}]'r'.replace("'r", "");
 JSON.parse(aa);

看小提琴:

http://jsfiddle.net/yr0u04cu/

您提供的字符串看起来像某个控制台日志,它不是有效的json字符串。但它可能被转化为一个有效的。

这将适用于一些简单的案例,这些案例可能正好符合您的需求。

var aa = "'[{key:10,key2:20}]''r";
var lead = aa.match(/^'s*['"]/)[0];
var trail = aa.match(/['"]'s*$/)[0];
aa = aa.substr(lead.length, aa.length - trail.length - 1);
aa = aa.replace(/('w+):/g, '"$1":');
var json = JSON.parse(aa);
json[0].key = 5;
var log = document.getElementById('log');
log.innerText = lead + JSON.stringify(json) + trail;
log.innerText += ''ntrail.length = ' + trail.length;
<pre id="log"></pre>

代码已更新。好吧,我知道你看不到"''r"这个词。别担心,它仍然在那里,因为你可以看到踪迹的长度是2。

如果您无法控制输入,您可能不得不使用eval()(尽管出于安全原因,我强烈反对(。如果可能的话,最好找到一种方法来获得原始输入以确认为JSON。

话虽如此,这对我来说很有效:

// Original string
var aa = "'[{key:10,key2:20}]''r";
// First, cleanup the trailing 'r
aa = aa.trim(); // may need to polyfill `.trim()`
// Need to get it to a JSO (JavaScript object)
var temp;
// Assign temp the value of your string.
eval('temp='+aa);
// next, evaluate that string as a JSO.
temp = eval(temp);
// make your changes
temp[0].key = 5;
// restore aa
aa = "'" + JSON.stringify(temp) + "''r";
// output to the <pre> for visibility
document.getElementById('out').textContent = aa;
<pre id="out"></pre>

根据输入中的差异,纯字符串方法可能是合适的。然而,这取决于可能使用的键的类型,并且'r会被字符串操作剥离。

    function replaceKeyValue(s, key, value) {
      // Build a regular expression to match the key and its value
      var re = new RegExp('(''W)' + key + ':[^,]+');
      // Replace the key with its new value
      return s.replace(re, '$1' + key + ':' + value);
    }
    var s = "'[{key:10,key2:20}]''r";
    
    document.write(replaceKeyValue(s, 'key', 5)); // '[{key:5,key2:20}]'