The Python Oracle

Single vs double quotes in JSON

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Track title: CC D Schuberts Piano Sonata D 850 in D

--

Chapters
00:00 Single Vs Double Quotes In Json
00:23 Accepted Answer Score 247
00:38 Answer 2 Score 203
00:52 Answer 3 Score 70
01:06 Answer 4 Score 23
02:28 Answer 5 Score 19
02:55 Thank you

--

Full question
https://stackoverflow.com/questions/4162...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #json

#avk47



ACCEPTED ANSWER

Score 256


JSON syntax is not Python syntax. JSON requires double quotes for its strings.




ANSWER 2

Score 210


you can use ast.literal_eval()

>>> import ast
>>> s = "{'username':'dfdsfdsf'}"
>>> ast.literal_eval(s)
{'username': 'dfdsfdsf'}



ANSWER 3

Score 72


You can dump JSON with double quote by:

import json

# mixing single and double quotes
data = {'jsonKey': 'jsonValue',"title": "hello world"}

# get string with all double quotes
json_string = json.dumps(data) 



ANSWER 4

Score 19


demjson is also a good package to solve the problem of bad json syntax:

pip install demjson

Usage:

from demjson import decode
bad_json = "{'username':'dfdsfdsf'}"
python_dict = decode(bad_json)

Edit:

demjson.decode is a great tool for damaged json, but when you are dealing with big amourt of json data ast.literal_eval is a better match and much faster.