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.

2
  • 4
    JSON has a specific format ... strings (and key names) are enclosed in " not ' - see documentation Commented Dec 5, 2017 at 3:25
  • Thanks, that solved it. Commented Dec 5, 2017 at 3:34

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

add some description to your answer.
technically, that's not JSON, that's an object - now, how to make that a string ...???

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.