简体   繁体   中英

How to convert string to json in Angular?

Starting to the following kind of string:

const json = '{"list":"[{"additionalInformation": {"source": "5f645d7d94-c6ktd"}, "alarmName": "data", "description": "Validation Error. Fetching info has been skipped.", "eventTime": "2020-01-27T14:42:44.143200 UTC", "expires": 2784, "faultyResource": "Data", "name": "prisco", "severity": "Major"}]"}'

How can I manage this as a JSON? The following approach doesn't work

const obj = JSON.parse(json );
unuspected result

How can I parse it correctly?

In conclusion, I should extract the part relative to the first item list and then parse the JSON that it contains.

Your JSON is invalid. The following is the valid version of your JSON:

const json= {
    "list": [ {
        "additionalInformation": {
            "source": "5f645d7d94-c6ktd"
        },
        "alarmName": "data",
        "description": "Validation Error. Fetching info has been skipped.",
        "eventTime": "2020-01-27T14:42:44.143200 UTC",
        "expires": 2784,
        "faultyResource": "Data",
        "name": "prisco",
        "severity": "Major"
      }
    ]
}

The above is already a JSON and parsing it as JSON again throws an error.

JSON.parse() parse string/ text and turn it into JavaScript object. The string/ text should be in a JSON format or it will throw an error.

Update: Create a function to clean your string and prepare it for JSON.parse() :

cleanString(str) {
    str = str.replace('"[', '[');
    str = str.replace(']"', ']');
  return str;
}

And use it like:

json = this.cleanString(json);
console.log(JSON.parse(json));

Demo:

 let json = '{"list":"[{"additionalInformation": {"source": "5f645d7d94-c6ktd"}, "alarmName": "data", "description": "Validation Error. Fetching info has been skipped.", "eventTime": "2020-01-27T14:42:44.143200 UTC", "expires": 2784, "faultyResource": "Data", "name": "prisco", "severity": "Major"}]"}'; json = cleanString(json); console.log(JSON.parse(json)); function cleanString(str) { str = str.replace('"[', '['); str = str.replace(']"', ']'); return str; }

删除数组括号周围的双引号以使 json 有效:

const json = '{"list":[{"additionalInformation": {"source": "5f645d7d94-c6ktd"}, "alarmName": "data", "description": "Validation Error. Fetching info has been skipped.", "eventTime": "2020-01-27T14:42:44.143200 UTC", "expires": 2784, "faultyResource": "Data", "name": "prisco", "severity": "Major"}]}'

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