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.
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)
I had similar problem . Two components communicating with each other was using a queue .
First component was not doing json.dumps before putting message to queue. So the JSON string generated by receiving component was in single quotes. This was causing error
Expecting property name enclosed in double quotes
Adding json.dumps started creating correctly formatted JSON & solved issue.
For anyone who wants a quick-fix, this simply replaces all single quotes with double quotes:
import json
predictions = []
def get_top_k_predictions(predictions_path):
'''load the predictions'''
with open (predictions_path) as json_lines_file:
for line in json_lines_file:
predictions.append(json.loads(line.replace("'", "\"")))
get_top_k_predictions("/sh/sh-experiments/outputs/john/baseline_1000/test_predictions.jsonl")
import ast
inpt = {'http://example.org/about': {'http://purl.org/dc/terms/title':
[{'type': 'literal', 'value': "Anna's Homepage"}]}}
json_data = ast.literal_eval(json.dumps(inpt))
print(json_data)
this will solve the problem.
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 have run into this problem multiple times when the JSON has been edited by hand. If someone was to delete something from the file without noticing it can throw the same error.
For instance, If your JSON last "}" is missing it will throw the same error.
So If you edit you file by hand make sure you format it like it is expected by the JSON decoder, otherwise you will run into the same problem.
Hope this helps!
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"}]}}
Quite simply, that string is not valid JSON. As the error says, JSON documents need to use double quotes.
You need to fix the source of the data.
It is always ideal to use the json.dumps()
method.
To get rid of this error, I used the following code
json.dumps(YOUR_DICT_STRING).replace("'", '"')
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
I had the same problem and what I did is to replace the single quotes with the double one, but what was worse is the fact I had the same error when I had a comma for the last attribute of the json object. So I used regex in python to replace it before using the json.loads()
function. (Be careful about the s at the end of "loads")
import re
with open("file.json", 'r') as f:
s = f.read()
correct_format = re.sub(", *\n *}", "}", s)
data_json = json.loads(correct_format)
The used regex return each comma followed by a newline and "}", replacing it just with a "}".
with open('input.json','r') as f:
s = f.read()
s = s.replace('\'','\"')
data = json.loads(s)
This worked perfectly well for me. Thanks.
JSON strings must use double quotes. The JSON python library enforces this so you are unable to load your string. Your data needs to look like this:
{"http://example.org/about": {"http://purl.org/dc/terms/title": [{"type": "literal", "value": "Anna's Homepage"}]}}
If that's not something you can do, you could use ast.literal_eval()
instead of json.loads()
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
Use the eval
function.
It takes care of the discrepancy between single and double quotes.
x = x.replace("'", '"')
j = json.loads(x)
Although this is the correct solution, but it may lead to quite a headache if there a JSON like this -
{'status': 'success', 'data': {'equity': {'enabled': True, 'net': 66706.14510000008, 'available': {'adhoc_margin': 0, 'cash': 1277252.56, 'opening_balance': 1277252.56, 'live_balance': 66706.14510000008, 'collateral': 249823.93, 'intraday_payin': 15000}, 'utilised': {'debits': 1475370.3449, 'exposure': 607729.3129, 'm2m_realised': 0, 'm2m_unrealised': -9033, 'option_premium': 0, 'payout': 0, 'span': 858608.032, 'holding_sales': 0, 'turnover': 0, 'liquid_collateral': 0, 'stock_collateral': 249823.93}}, 'commodity': {'enabled': True, 'net': 0, 'available': {'adhoc_margin': 0, 'cash': 0, 'opening_balance': 0, 'live_balance': 0, 'collateral': 0, 'intraday_payin': 0}, 'utilised': {'debits': 0, 'exposure': 0, 'm2m_realised': 0, 'm2m_unrealised': 0, 'option_premium': 0, 'payout': 0, 'span': 0, 'holding_sales': 0, 'turnover': 0, 'liquid_collateral': 0, 'stock_collateral': 0}}}}
Noticed that "True" value? Use this to make things are double checked for Booleans. This will cover those cases -
x = x.replace("'", '"').replace("True", '"True"').replace("False", '"False"').replace("null", '"null"')
j = json.loads(x)
Also, make sure you do not make
x = json.loads(x)
It has to be another variable.
I've checked your JSON data
{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}
in http://jsonlint.com/ and the results were:
Error: Parse error on line 1:
{ 'http://example.org/
--^
Expecting 'STRING', '}', got 'undefined'
modifying it to the following string solve the JSON error:
{
"http://example.org/about": {
"http://purl.org/dc/terms/title": [{
"type": "literal",
"value": "Anna's Homepage"
}]
}
}
Source: Stackoverflow.com