gpt4 book ai didi

javascript - 向 JSON 对象字符串添加递增数字,使它们唯一

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:19:38 24 4
gpt4 key购买 nike

我有一个作为字符串传递给我的 JSON 对象,但是字符串形式的对象包含重复的属性。我需要临时向 Properties 添加递增的数字,以避免出现重复的 JSON 属性的问题。完成对对象的编辑后,我会将对象 JSON.Stringify 回字符串并删除数字。

这是我传递的字符串:

{
"View":{
"Image":{
"BackgroundImage":"Image.png",
"Position":[0,0],
"Width":320,
"Height":480
},
"Button":{
"BackgroundImage":"ButtonTop.png",
"Position":[61,83],
"Width":217,
"Height":58
},
"Button":{
"BackgroundImage":"ButtonBottom.png",
"Position":[61,214],
"Width":205,
"Height":73
},
"TextField":{
"BackgroundImage":"TextFieldLogin.png",
"Position":[102,336],
"Width":189,
"Height":31
},
"Label":{
"Position":[137,100],
"Width":72,
"Height":20,
"Text":"Hi Steve",
"FontSize":18,
"Color":[0,0,0,1]
},
"Label":{
"Position":[43,342],
"Width":54,
"Height":20,
"Text":"Login:",
"FontSize":18,
"Color":[0,0,0,1]
},
"Label":{
"Position":[115,234],
"Width":54,
"Height":20,
"Text":"Button",
"FontSize":18,
"Color":[0,0,0,1]
}
}
}

这是我希望的输出方式:

{
"View_1":{
"Image_1":{
"BackgroundImage":"Image.png",
"Position":[0,0],
"Width":320,
"Height":480
},
"Button_1":{
"BackgroundImage":"ButtonTop.png",
"Position":[61,83],
"Width":217,
"Height":58
},
"Button_2":{
"BackgroundImage":"ButtonBottom.png",
"Position":[61,214],
"Width":205,
"Height":73
},
"TextField_1":{
"BackgroundImage":"TextFieldLogin.png",
"Position":[102,336],
"Width":189,
"Height":31
},
"Label_1":{
"Position":[137,100],
"Width":72,
"Height":20,
"Text":"Hi Steve",
"FontSize":18,
"Color":[0,0,0,1]
},
"Label_2":{
"Position":[43,342],
"Width":54,
"Height":20,
"Text":"Login:",
"FontSize":18,
"Color":[0,0,0,1]
},
"Label_3":{
"Position":[115,234],
"Width":54,
"Height":20,
"Text":"Button",
"FontSize":18,
"Color":[0,0,0,1]
}
}
}

如何使用 javascript .replace() 按需添加编号,然后按需删除编号?

最佳答案

这个怎么样?我同意其他人的意见,建议无论是谁提供这个“JSON”,都应负责提供有效的语法,但除非有这种可能性,否则这可能会让你开始:

function formatJSON(input) {
return input.replace(/"([^"]+?)":{(.+)}/g, function(string, key, value) {
var dict = {};
return '"' + key + '":{' + value.replace(/"([^"]+?)":{(.+?)}/g, function(string, key, value) {
dict[key] = dict[key] == undefined ? 1 : ++dict[key];
return '"' + key + '_' + dict[key] + '":{' + formatJSON(value) + '}';
}) + '}';
});
};

JSFiddle:http://jsfiddle.net/WYkAT/

请注意,这将无法重命名更复杂、更深的 JSON 字符串上的所有键。它可以很容易地修改为更具递归性并且不那么针对您的特定情况,但可能会导致性能下降。如果您需要一个成熟的解决方案,我会考虑修改现有的 JSON.parse polyfill。这里有两个(JSON2 和 JSON3):

  1. https://github.com/douglascrockford/JSON-js
  2. https://github.com/bestiejs/json3

关于javascript - 向 JSON 对象字符串添加递增数字,使它们唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14299710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com