簡體   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