Shishir Pandey
Shishir Pandey

Reputation: 832

Loading python string with 'u' as json

I have a string in the following strings

json_string = '{u"favorited": false, u"contributors": null}'
json_string1 = '{"favorited": false, "contributors": null}'

The following json load works fine.

json.loads(json_string1 )

But, the following json load give me value error, how to fix this?

json.loads(json_string)
ValueError: Expecting property name: line 1 column 2 (char 1)

Upvotes: 2

Views: 5093

Answers (3)

Roee Anuar
Roee Anuar

Reputation: 3448

I faced the same problem with strings I received from a customer. The strings arrived with u's. I found a workaround using the ast package:

import ast
import json

my_str='{u"favorited": false, u"contributors": null}'
my_str=my_str.replace('"',"'")
my_str=my_str.replace(': false',': False')
my_str=my_str.replace(': null',': None')
my_str = ast.literal_eval(my_str)
my_dumps=json.dumps(my_str)
my_json=json.loads(my_dumps)

Note the replacement of "false" and "null" by "False" and "None", since the literal_eval only recognizes specific types of Python literal structures. This means that if you may need more replacements in your code - depending on the strings you receive.

Upvotes: 2

Mark Tolonen
Mark Tolonen

Reputation: 178115

Use json.dumps to convert a Python dictionary to a string, not str. Then you can expect json.loads to work:

Incorrect:

>>> D = {u"favorited": False, u"contributors": None}
>>> s = str(D)
>>> s
"{u'favorited': False, u'contributors': None}"
>>> json.loads(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\dev\Python27\lib\json\__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "D:\dev\Python27\lib\json\decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "D:\dev\Python27\lib\json\decoder.py", line 380, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

Correct:

>>> D = {u"favorited": False, u"contributors": None}
>>> s = json.dumps(D)
>>> s
'{"favorited": false, "contributors": null}'
>>> json.loads(s)
{u'favorited': False, u'contributors': None}

Upvotes: 0

Steve
Steve

Reputation: 46

You could remove the u suffix from the string using REGEX and then load the JSON

s = '{u"favorited": false, u"contributors": null}'
json_string = re.sub('(\W)\s*u"',r'\1"', s)
json.loads(json_string )

Upvotes: 1

Related Questions