Home > Net >  Why is json.loads throwing JSONDecodeError: Expecting value
Why is json.loads throwing JSONDecodeError: Expecting value

Time:01-06

I have a string like:

j = '{"type":"x","key":"A","attributes":{"label":"test","visible":True,"advancedOptions":True},"fees":[{"type":"set","key":"fee","attributes":{"amount":"5","type":"percent","label":"Test","fee":{"value":"7","type":"percent"},"visible":True}}]}'

I'm just wondering why this code works:

exec('t = '   j)
print(json.dumps(t, indent=4))

but this code doesn't

print(json.dumps(json.load(j), indent=4))

It doesn't make sense to me that if a string is first converted into a dictionary, you can load it as json, but you can't convert that exact same string into a json directly %\ ...

JSONDecodeError: Expecting value line 1 column 40 (char 39)

Has anyone run into anything like this before?

I read somewhere on the internet that it might have something to do with the size of the string, where json loads just can't handle it or something.

CodePudding user response:

Your data is not JSON (e.g. True is not JSON) but Python.

You can use ast.literal_eval() instead of json.loads() on that string to parse it as a Python literal and end up with a dict.

>>> import ast
>>> j = '{"type":"x","key":"A","attributes":{"label":"test","visible":True,"advancedOptions":True},"fees":[{"type":"set","key":"fee","attributes":{"amount":"5","type":"percent","label":"Test","fee":{"value":"7","type":"percent"},"visible":True}}]}'
>>> ast.literal_eval(j)
{'type': 'x', 'key': 'A', 'attributes': {'label': 'test', 'visible': True, 'advancedOptions': True}, 'fees': [{'type': 'set', 'key': 'fee', 'attributes': {'amount': '5', 'type': 'percent', 'label': 'Test', 'fee': {'value': '7', 'type': 'percent'}, 'visible': True}}]}
  • Related