I try parsing a very simple json string I get from the net: {"price" : '10.25'} As you can see, the number (10.25) is between single quotes and it seems to be a problem for simple json:
Reproduction:
import simplejson as json
json_str = """ {"price" : '10.25'} """
json.loads(json_str)
Result:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/pymodules/python2.5/simplejson/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/usr/lib/pymodules/python2.5/simplejson/decoder.py", line 335, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/pymodules/python2.5/simplejson/decoder.py", line 353, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
However, if I change the single quotes to double ones - it works.\ Unfortunately, the jsons I get are not as simple as in the example above, so I can't just replace all single quotes with string replace command.
Anybody knows what is the right way to parse this json?
P.S. I use python 2.5.
Thanks a lot!
{"price" : "10.25"} , JSON contains double quotes only.
The JSON with single quotes is invalid ( see : www.jsonlint.com ) :
Parse error on line 2:
{ "price": '10.25'}
--------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
You can correct your json using regex replace, or use ast.literal eval to load it as python object ( or dump it as json and load it again )
>>> a = """ {"price" : '10.25'} """
>>> import ast
>>> new_dict = ast.literal_eval(a.strip())
>>> import json
>>> json.dumps(new_dict)
'{"price": "10.25"}'
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