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/
In my case, double quotes was not a problem.
Last comma gave me same error message.
{'a':{'b':c,}}
^
To remove this comma, I wrote some simple code.
import json
with open('a.json','r') as f:
s = f.read()
s = s.replace('\t','')
s = s.replace('\n','')
s = s.replace(',}','}')
s = s.replace(',]',']')
data = json.loads(s)
And this worked for me.
I used this method and managed to get the desired output. my script
x = "{'inner-temperature': 31.73, 'outer-temperature': 28.38, 'keys-value': 0}"
x = x.replace("'", '"')
j = json.loads(x)
print(j['keys-value'])
output
>>> 0
As it clearly says in error, names should be enclosed in double quotes instead of single quotes. The string you pass is just not a valid JSON. It should look like
{"http://example.org/about": {"http://purl.org/dc/terms/title": [{"type": "literal", "value": "Anna's Homepage"}]}}
As the other answers explain well the error occurs because of invalid quote characters passed to the json module.
In my case I continued to get the ValueError even after replacing '
with "
in my string. What I finally realized was that some quote-like unicode symbols had found their way into my string:
“ ” ‛ ’ ‘ ` ´ ″ ′
To clean all of these you can just pass your string through a regular expression:
import re
raw_string = '{“key”:“value”}'
parsed_string = re.sub(r"[“|”|‛|’|‘|`|´|″|′|']", '"', my_string)
json_object = json.loads(parsed_string)
with open('input.json','r') as f:
s = f.read()
s = s.replace('\'','\"')
data = json.loads(s)
This worked perfectly well for me. Thanks.
as JSON only allows enclosing strings with double quotes you can manipulate the string like this:
str = str.replace("\'", "\"")
if your JSON holds escaped single-quotes (\'
) then you should use the more precise following code:
import re
p = re.compile('(?<!\\\\)\'')
str = p.sub('\"', str)
This will replace all occurrences of single quote with double quote in the JSON string str
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