繁体   English   中英

How can i convert my string output into the object so that i get json as a output using javascript?

[英]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
}

我有这个 output 作为string

如何将其转换为object

这就是我进行转换的方式:

`

{
  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;
});

如果您可以更改创建字符串的方式,那将会很有帮助。 这可能允许您简单地使用 JSON.parse。 如果这不可能,您需要将字符串转换为有效的 JSON。 这表示:

  • 将所有键用双引号括起来
  • 将字符串和日期值用双引号括起来
  • 将单个对象分成单独的字符串
  • 用两个双引号替换所有空值

我的方法是用括号split字符串,然后在每个冒号和逗号前后添加双引号,确保考虑到边缘情况。

有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

您可以为不存在的值添加 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM