Coderaemon
Coderaemon

Reputation: 3877

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.

Upvotes: 157

Views: 250857

Answers (13)

Oliver Gaida
Oliver Gaida

Reputation: 1930

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

Upvotes: 2

Surya R Praveen
Surya R Praveen

Reputation: 3745

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

Upvotes: 1

Marcellia
Marcellia

Reputation: 212

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

Upvotes: -1

Ramu Narasinga
Ramu Narasinga

Reputation: 436

Add an escape for your double quotes like the following:

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

Upvotes: 0

Sean AH
Sean AH

Reputation: 523

// 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.

Upvotes: 8

user1941464
user1941464

Reputation: 21

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.

Upvotes: -4

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

Upvotes: 22

Vaishnavi Dongre
Vaishnavi Dongre

Reputation: 259

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

This solved the problem for me.

Upvotes: 8

greg miller
greg miller

Reputation: 25

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

Upvotes: -14

Min
Min

Reputation: 580

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>

Upvotes: 57

aup
aup

Reputation: 810

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>

Upvotes: 7

ssube
ssube

Reputation: 48347

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.

Upvotes: 128

Jonathan.Brink
Jonathan.Brink

Reputation: 25453

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.

Upvotes: 8

Related Questions