Parsing string as JSON with single quotes?

I have a string

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

How can I parse above string (str) to JSON ? This seems like a simple parsing; it's not working somehow.



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>

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 = 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()


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}';


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

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

This solved the problem for me.

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

Something like this:

var div = document.getElementById("result");

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


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.