简体   繁体   中英

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 .

How can I convert this into an 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. If this isn't possible, you'll need to transform you string into valid JSON. This means:

  • wrapping all keys in double quotes
  • wrapping string and date values in double quotes
  • separating individual objects into separate strings
  • replacing all empty values with two double quotes

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.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse for more details

You can add none for values that are not present and add quotes to keys.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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