我有以下代码,它接受一个字符串并将其转换为一个对象。问题是字符串包含多个重复的键,当变成一个对象时,它只识别最后一个。
这是我的工作演示http://jsfiddle.net/Qt92d/
这是我的代码:
var str = 'View\n{\n Name: View1;\n Image\n {\n BackgroundImage: Image.gif;\n Position: 0, 0;\n Width: 320;\n Height: 480;\n }\n\n Button\n {\n BackgroundImage: Button.gif;\n Transition: View2;\n Position: 49, 80;\n Width: 216;\n Height: 71;\n }\n\n Button\n {\n BackgroundImage: Button2.gif;\n Position: 65, 217;\n Width: 188;\n Height: 134;\n }\n\n Label\n {\n Position: 106, 91;\n Width: 96;\n Height: 34;\n Text: "Button";\n FontSize: 32;\n Color: 0.12549, 0.298039, 0.364706, 1;\n }\n Scroll\n {\n Position: 106, 91;\n Width: 96;\n Height: 34;\n Button{\n BackgroundImage: Button2.gif;\n Position: 65, 217;\n Width: 188;\n Height: 134;\n }\n Button{\n BackgroundImage: Button2.gif;\n Position: 65, 217;\n Width: 188;\n \n Height: 134;\n }\n\n }\n\n}';
str = str.replace(/(\w+)\s*\{/g, "$1:{"); // add in colon after each named object
str = str.replace(/\}(\s*\w)/g, "},$1"); // add comma before each new named object
str = str.replace(/;/g, ","); // swap out semicolons with commas
str = str.replace(/,(\s+\})/g, "$1"); // get rid of trailing commas
str = str.replace(/([\d\.]+(, [\d\.]+)+)/g, "[$1]"); // create number arrays
str = str.replace(/"/g, ""); // get rid of all double quotes
str = str.replace(/:\s+([^\[\d\{][^,]+)/g, ':"$1"'); // create strings
$("pre").html(str);
var obj;
eval("obj={" + str + "};");
这是上面代码的输出。请注意,有多个“按钮”。这就是问题开始的地方。
View:{
Name:"View1",
Image:{
BackgroundImage:"Image.gif",
Position: [0, 0],
Width: 320,
Height: 480
},
Button:{
BackgroundImage:"Button.gif",
Transition:"View2",
Position: [49, 80],
Width: 216,
Height: 71
},
Button:{
BackgroundImage:"Button2.gif",
Position: [65, 217],
Width: 188,
Height: 134
},
Label:{
Position: [106, 91],
Width: 96,
Height: 34,
Text:"Button",
FontSize: 32,
Color: [0.12549, 0.298039, 0.364706, 1]
},
Scroll:{
Position: [106, 91],
Width: 96,
Height: 34,
Button:{
BackgroundImage:"Button2.gif",
Position: [65, 217],
Width: 188,
Height: 134
},
Button:{
BackgroundImage:"Button2.gif",
Position: [65, 217],
Width: 188,
Height: 134
}
}
}
我试图弄清楚如何在每个键的末尾添加一个自动递增的数字,即视图、名称、按钮、图像等