Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do single quote( ' ) and double quote( " ) get different results in python's json module?

Tags:

python

json

I have such piece of python code:

import json
single_quote = '{"key": "value"}'
double_quote = "{'key': 'value'}"
data = json.loads(single_quote) # get a dict: {'key': 'value'}
data = json.loads(double_quote) # get a ValueError: Expecting property name: line 1 column 2 (char 1)

In python, single_quote and double_quote make no technical differences, don't they? Then why single_quote works and double_quote doesn't?

like image 787
Java Xu Avatar asked Dec 01 '22 17:12

Java Xu


2 Answers

That's because only the first example is valid JSON. JSON data have keys and values surrounded by "..." and not '...'.

There are other "rules" that you may not be expecting. There's a great list on this wikipedia page here. For example, booleans should be lowercase (true and false) and not True and False. JSON != Python.

like image 174
TerryA Avatar answered Dec 17 '22 20:12

TerryA


It's not the outside quotes that matter, it's the literal quotes in the JSON string (must be ")

ie. This is ok (but cumbersome)

double_quote = "{\"key\": \"value\"}"

You can also use triple quotes

'''{"key": "value"}'''
"""{"key": "value"}"""

The choices of quotes are there so you hardly ever need to use the ugly/cumbersome versions

like image 37
John La Rooy Avatar answered Dec 17 '22 20:12

John La Rooy