admin管理员组

文章数量:1131471

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.

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.

Share Improve this question edited Feb 14, 2024 at 16:30 phuzi 13.1k4 gold badges28 silver badges59 bronze badges asked Mar 16, 2016 at 14:23 CoderaemonCoderaemon 3,8577 gold badges30 silver badges52 bronze badges 9
  • 17 Single quotes are not correctly formatted json, so if you're receiving something like that, you'd probably need to use str.replace() and replace single qoutes with " before trying to parse it – aup Commented Mar 16, 2016 at 14:27
  • 2 You should anyway always try to use single quotes for strings in javascript. var str = "bad example"; is not good practice, better do the following: var str = 'good example'; => like this you won't have any problems with JSON and you wont have any problems with HTML either. :) – ReeCube Commented Mar 16, 2016 at 14:30
  • 6 @ReeCube That seems little more than an opinion--there's no problem with HTML anyway, it accepts both. For JSON, why create it with strings anyway? I don't actually recall the last time I built JSON out of anything other than an object. – Dave Newton Commented Mar 16, 2016 at 14:33
  • the whole web development is a mess. and enforce strict rule for no discerning reason seems stupid. IMO.. where is good reason to allow swapping single and double quote at will.. it works in python. and it should work in json. for example try to write hardcoded json in your code and you get bunch of escaped quotes.. so many that you can hardly read which defies purpose of json as a clean text format.. the dev community sways from one extreme to another without hanging on a reasonable ground. – Boppity Bop Commented Mar 15, 2023 at 13:36
  • 1 8 years, crazy how the time goes... thank you for reviving this discussion @phuzi – ReeCube Commented Mar 6, 2024 at 20:59
 |  Show 4 more comments

13 Answers 13

Reset to default 125

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

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.

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

This solved the problem for me.

// regex uses look-forwards and look-behinds to select only single-quotes that should be selected
const regex = /('(?=(,\s*')))|('(?=:))|((?<=([:,]\s*))')|((?<={)')|('(?=}))/g;
str = str.replace(regex, '"');
str = JSON.parse(str);

The other answers simply do not work in enough cases. Such as the above cited case: "title": "Mama's Friend", it naively will convert the apostrophe unless you use regex. JSON5 will want the removal of single quotes, introducing a similar problem.

Warning: although I believe this is compatible with all situations that will reasonably come up, and works much more often than other answers, it can still break in theory.

Something like this:

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

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

sometimes you just get python data, it looks a little bit like json but it is not. If you know that it is pure python data, then you can eval these data with python and convert it to json like this:

echo "{'a':1}" | /usr/bin/python3 -c "import json;print(json.dumps(eval(input())))"

Output:

{"a": 1}

this is good json.

if you are in JavaScript, then you could use JSON.stringify like this:

data = {'id': 74,'parentId': null};
console.log(JSON.stringify(data));

Output:

> '{"id":74,"parentId":null}'

If your api throws errors unless your JSON double quotes are escaped ("{"foo": true}"), all you need to do is stringify twice e.g. JSON.stringify(JSON.stringify(bar))

newFaqJsonUpdate = JSON.stringify(JSON.stringify(faqJsonUpdate));

Add an escape for your double quotes like the following:

str = "{\"a\":1}";
JSON.parse(str);
console.log(str)

A little late to the party - but this is what helped me (Python)

Import Json - Python has the built-in module json, which allows us to work with JSON data.

import json  

Print the JSON data with indentation

print(json.dumps(str_json_data, indent=4))

Write the JSON data in a file

with open("test.json", "w") as file:
     file.write(json.dumps(str_json_data, indent=4))
        

If you assume that the single-quoted values are going to be displayed, then instead of this:

str = str.replace(/\'/g, '"');

you can keep your display of the single-quote by using this:

str = str.replace(/\'/g, '\&apos;\');

which is the HTML equivalent of the single quote.

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

本文标签: javascriptParsing string as JSON with single quotesStack Overflow