[英]How can i convert my string output into the object so that i get json as a output using javascript?
{
from: ,
to: ,
title: xyz,
id: 1
}, {
from:,
to: ,
title: xyz,
id: 2
}
I have this output as a string
.我有这个 output 作为string
。
How can I convert this into an object
?如何将其转换为object
?
This is how I do the transformation:这就是我进行转换的方式:
`
{
from: 1999 - 03 - 11 T00: 00: 00 Z,
to: 2099 - 12 - 31 T00: 00: 00 Z,
title: Standard,
isAllDay: false,
color: ,
colorText: ,
repeatEvery: 5,
id: 1
}, {
from: 1999 - 03 - 11 T00: 00: 00 Z,
to: 2099 - 12 - 31 T00: 00: 00 Z,
title: Standard,
isAllDay: false,
color: ,
colorText: ,
repeatEvery: 1,
id: 2
}
`.trim().split("}, {").map(item => {
let rawData = item.split("\n").filter(it => it.length && (it.replace("{", "}").indexOf("}") === -1)).map(it => {return {key: it.substring(0, it.indexOf(":")).trim(), value: it.substring(it.indexOf(":") + 1)}}).map(it => {return it.value.endsWith(",") ? {key: it.key, value: it.value.slice(0, -1)} : it});
let output = {};
for (let d of rawData) output[d.key] = d.value;
return output;
});
It would be helpful if you could change the way that string is created.如果您可以更改创建字符串的方式,那将会很有帮助。 This may allow you to simply use JSON.parse.这可能允许您简单地使用 JSON.parse。 If this isn't possible, you'll need to transform you string into valid JSON.如果这不可能,您需要将字符串转换为有效的 JSON。 This means:这表示:
My approach would be to split
the string by brackets, then add double quotes before and after each colon and comma, making sure to account for edge cases.我的方法是用括号split
字符串,然后在每个冒号和逗号前后添加双引号,确保考虑到边缘情况。
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse for more details有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
You can add none for values that are not present and add quotes to keys.您可以为不存在的值添加 none 并为键添加引号。
var s = `{
from:,
to: ,
title:xyz,
id: 1
}, {
from: ,
to:,
title:xyz,
id: 2
}`;
s = s.replace(/(\r\n|\n|\r| |\t|)/g, "");
var res = "";
var commafound = 1;
for (var i=0; i<s.length; i++) {
if (s[i]==':') {
if ((i+1<s.length) && (s[i+1]==',' || s[i+1]=='}')) {
res += "\"" + s[i] + "\"" + "none";
}
else if (commafound==1) {
commafound = 0;
res += "\"" + s[i] + "\"";
}
else {
res += s[i];
}
}
else if (s[i]==',') {
commafound = 1;
if (s[i-1]!='}' && s[i+1]!='{')
res += "\"" + s[i] + "\"";
else res += s[i];
}
else if (s[i]=='{') res += s[i] + "\"";
else if (s[i]=='}') res += "\"" + s[i];
else {
res += s[i];
}
}
s = '[' + String(res) + ']';
var json = JSON.parse(s);
console.log(json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.