Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing string as JSON with single quotes?

I have a string

str = "{'a':1}"; JSON.parse(str); VM514:1 Uncaught SyntaxError: Unexpected token '(…) 

How can I parse the above string (str) into a JSON object ?

This seems like a simple parsing. It's not working though.

like image 586
Coderaemon Avatar asked Mar 16 '16 14:03

Coderaemon


People also ask

Can JSON strings have single quotes?

Strings in JSON are specified using double quotes, i.e., " . If the strings are enclosed using single quotes, then the JSON is an invalid JSON .

Does JSON use double or single quotes?

JSON only allows double quotes (unless you control the data, and can use a library that is more liberal at parsing JSON - but a JSON file with single quotes is not truly a JSON file)

Do I need to escape single quote in JSON?

In JSON, you don't need to escape single quotes inside a value that is enclosed with double-quotes. In the case that you have double quotes as part of a value (that is enclosed with double quotes) then you would need to escape them.

How do I parse a string in JSON?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.


1 Answers

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.

like image 177
ssube Avatar answered Sep 28 '22 09:09

ssube