'Can't convert JSON string to Javascript object
I am trying to convert JSON string to javascript object, but unsuccessfully.
This is my code:
result = "{'image': 'https://google.com/16469374645-11-12-05-27-10-2017.jpg', 'sender': 'Test test123', 'text': 'Test 005', 'expiry': '2016-10-15 01:51:28', 'points': 650, 'color_from': '#8DBCC5', 'color_to': '#13717C'}";
result = JSON.parse(result);
console.log(result);
alert(result);
I have created a fiddle with a demo. https://jsfiddle.net/030u9z9f/1/
It seems like my JSON is not properly formatted, but I am not sure how to adjust it.
Solution 1:[1]
There JSON does not contain any single quote for there key and value description you have change all '
to "
for the same string. There all the Key and Value should be enquoted by "
and a complete string of JSON must be enclosed with '
for better string conversion.
The JSON standard requires double quotes and will not accept single quotes, nor will the parser.
If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"') and you should end up with valid JSON. check ...
result = '{"image": "https://google.com/16469374645-11-12-05-27-10-2017.jpg", "sender": "Test test123", "text": "Test 005", "expiry": "2016-10-15 01:51:28", "points": 650, "color_from": "#8DBCC5", "color_to": "#13717C"}';
result = JSON.parse(result);
console.log(result);
alert(result);
Solution 2:[2]
Try using this JSON,
{
"image": "https://google.com/16469374645-11-12-05-27-10-2017.jpg",
"sender": "Test test123",
"text": "Test 005",
"expiry": "2016-10-15 01:51:28",
"points": 650,
"color_from": "#8DBCC5",
"color_to": "#13717C"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | A.D. |
Solution 2 | Ku Syafiq |