Python simplejson does not parse plain json string

I am trying to parse a very simple json string that I am getting from the net: {"price": '10 .25 '} As you can see the number (10.25) is between single quotes and this seems to be a problem for plain 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 quotes - it works. \ Unfortunately, the jsons I get are not as simple as the example above, so I can't just replace all single quotes with a string replacement command.

Does anyone know how to parse this json correctly?

PS I am using python 2.5.

Thank you so much!

+3


source to share


4 answers


{"price" : "10.25"}

, JSON contains only double quotes.

JSON with single quotes is not allowed (see: www.jsonlint.com):

Parse error on line 2:
{    "price": '10.25'}
--------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

      



You can fix your json using regex substitution or use ast.literal eval to load it as a 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"}'

      

+3


source


Single quotes are not valid JSON, so simplejson does exactly what it should be. Unfortunately the problem is with the JSON you are getting. I don't see a situation where a little regex-fu can't help you find and replace the single quotes you need.



0


source


A value should not be specified if it is only numeric or must be double. So the correct way to do it is:

import simplejson as json
json_str = """ {"price" : 10.25} """
json.loads(json_str)

      

And to replace it you can parse the json string with some regluar expression using finditer for example

0


source


Check the JSON format is correct on json.org .

As you can see there, only double quote is valid for string (dictionary key).

0


source







All Articles