Prisco
Prisco

Reputation: 733

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.

Upvotes: 1

Views: 11774

Answers (2)

Maihan Nijat
Maihan Nijat

Reputation: 9334

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

Upvotes: 3

JMP
JMP

Reputation: 1934

Remove the double quotes from around the array brackets to make the json valid:

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"}]}'

Upvotes: 0

Related Questions