I've been trying to figure out a good way to load JSON objects in Python. I send this json data:
{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}
to the backend where it will be received as a string then I used json.loads(data)
to parse it.
But each time I got the same exception :
ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
I googled it but nothing seems to work besides this solution json.loads(json.dumps(data))
which personally seems for me not that efficient since it accept any kind of data even the ones that are not in json format.
Any suggestions will be much appreciated.
The Python "JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)" occurs when we try to parse an invalid JSON string (e.g. single-quoted keys or values, or a trailing comma). Use the ast. literal_eval() method to solve the error.
JSON names require double quotes.
8. Can you use a double quote inside a JSON string? Yes, if you use the ascii code.
As you can see from the code snippet, single quotes break JSON parsing. The technical reason has to do with the JSON specification (RFC 7159), which requires double quotes as the JSON string character.
This:
{
'http://example.org/about': {
'http://purl.org/dc/terms/title': [
{'type': 'literal', 'value': "Anna's Homepage"}
]
}
}
is not JSON.
This:
{
"http://example.org/about": {
"http://purl.org/dc/terms/title": [
{"type": "literal", "value": "Anna's Homepage"}
]
}
}
is JSON.
EDIT:
Some commenters suggested that the above is not enough.
JSON specification - RFC7159 states that a string begins and ends with quotation mark. That is "
.
Single quoute '
has no semantic meaning in JSON and is allowed only inside a string.
as JSON only allows enclosing strings with double quotes you can manipulate the string like this:
s = s.replace("\'", "\"")
if your JSON holds escaped single-quotes (\'
) then you should use the more precise following code:
import re
p = re.compile('(?<!\\\\)\'')
s = p.sub('\"', s)
This will replace all occurrences of single quote with double quote in the JSON string s
and in the latter case will not replace escaped single-quotes.
You can also use js-beautify
which is less strict:
$ pip install jsbeautifier
$ js-beautify file.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With