[javascript] 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.

This question is related to javascript json

The answer is


Using single quotes for keys are not allowed in JSON. You need to use double quotes.

For your use-case perhaps this would be the easiest solution:

str = '{"a":1}';

Source:

If a property requires quotes, double quotes must be used. All property names must be surrounded by double quotes.


Something like this:

_x000D_
_x000D_
var div = document.getElementById("result");_x000D_
_x000D_
var str = "{'a':1}";_x000D_
  str = str.replace(/\'/g, '"');_x000D_
  var parsed = JSON.parse(str);_x000D_
  console.log(parsed);_x000D_
  div.innerText = parsed.a;
_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_


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.


I know it's an old post, but you can use JSON5 for this purpose.

<script src="json5.js"></script>
<script>JSON.stringify(JSON5.parse('{a:1}'))</script>

If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.

var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');

The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()


json = ( new Function("return " + jsonString) )(); 

var str =  "{'a':1}";
str = str.replace(/'/g, '"')
obj = JSON.parse(str);
console.log(obj);

This solved the problem for me.