1

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.

Bob
  • 8,392
  • 12
  • 55
  • 96

2 Answers2

4

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

Fiddle

Ref

A.D.
  • 2,352
  • 2
  • 15
  • 25
1

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"
}
Ku Syafiq
  • 63
  • 6