我有来自用户的以下字符串,需要将其转换为JSON。
2r,5g|3b,2r,4y|3g
我想用JavaScript将其转换为JSON。以下是我希望JSON的样子:
rounds = {
"round" : {
"interval" : {
"time" : "2",
"color" : "r"
},
"interval" : {
"time" : "5",
"color" : "g"
}
},
"round" : {
"interval" : {
"time" : "3",
"color" : "b"
},
"interval" : {
"time" : "2",
"color" : "r"
},
"interval" : {
"time" : "4",
"color" : "y"
}
},
"round" : {
"interval" : {
"time" : "3",
"color" : "g"
}
}
}
我不确定从哪里开始,所以感谢任何帮助!
答案 0 :(得分:2)
您可以使用此代码:
var strRounds = "2r,5g|3b,2r,4y|3g";
var roundsSplit = strRounds.split("|");
var rounds = {};
for (var i = 0; i < roundsSplit.length; i++){
var intervalsSplit = roundsSplit[i].split(",");
if (intervalsSplit.length > 0){
rounds["round" + i] = {};
}
for (var j = 0; j < intervalsSplit.length; j++){
rounds["round" + i]["interval" + j] = {
"time": intervalsSplit[j][0],
"color": intervalsSplit[j][1]
};
}
}
但我不得不说,你写的JSON无效,因为它的'字段必须有唯一的名称。我使用了round0
,round1
...和interval0
之类的名字等等。
答案 1 :(得分:0)
将字符串拆分为“|”获得新一轮,然后将每个子字符串拆分为“,”以获得该轮的间隔。
因此,您可以轻松创建javascript地图,然后使用Map to JSON转换来获取所需的JSON。
答案 2 :(得分:0)
您提供的格式不是有效的JSON,因为您有多个相同密钥的实例。以下是通过使用数组而不是具有相同键的多个实例的对象来尝试更加理智的东西:
function userStringToJSON(userString) {
var arrayOfRounds = userString.split("|").map(function (roundString) {
return roundString.split(",").map(function (intervalString) {
var time = parseInt(intervalString, 10) + "";
var color = intervalString.substring(time.length);
return { time: time, color: color };
});
});
return JSON.stringify(arrayOfRounds);
}
然后userStringToJSON("2r,5g|3b,2r,4y|3g")
给出字符串:
[[{"time":"2","color":"r"},{"time":"5","color":"g"}],[{"time":"3","color":"b"},{"time":"2","color":"r"},{"time":"4","color":"y"}],[{"time":"3","color":"g"}]]
,相当于
给出的对象数组的JavaScript数组[
[
{ time: "2", color: "r" },
{ time: "5", color: "g" }
],
[
{ time: "3", color: "b" },
{ time: "2", color: "r" },
{ time: "4", color: "y" }
],
[
{ time: "3", color: "g" }
]
]
答案 3 :(得分:0)
我不知道这对你有多大帮助,但它完全符合你的需要:
<script>
var string = "2r,5g|3b,2r,4y|3g";
var inSplit = string.split('|');
var myJson = "rounds = { ";
for (var one = 0; one < inSplit.length; one++){
var inOne = inSplit[one].split(',');
myJson = myJson + '\n "round" : {';
for (var rnd = 0; rnd < inOne.length; rnd++){
val = inOne[rnd].split('');
myJson = myJson + '\n "interval" : {';
myJson = myJson + '\n "time" : "'+val[0]+'",';
myJson = myJson + '\n "color" : "'+val[1]+'"';
myJson = myJson + '\n }';
if(inOne.length > (rnd+1)){
myJson = myJson + ',';
}
}
myJson = myJson + '\n }';
if(inSplit.length > (one+1)){
myJson = myJson + ',';
}
}
myJson = myJson + '\n}';
document.write(myJson);
</script>
查看jsfiddle