Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to make simplejson less strict?

I'm interested in having simplejson.loads() successfully parse the following:

{foo:3}

It throws a JSONDecodeError saying "expecting property name" but in reality it's saying "I require double quotes around my property names". This is annoying for my use case, and I'd prefer a less strict behavior. I've read the docs, but beyond making my own decoder class, I don't see anything obvious that changes this behavior.

like image 696
slacy Avatar asked Feb 01 '12 23:02

slacy


3 Answers

You can use YAML (>=1.2)as it is a superset of JSON, you can do:

>>> import yaml
>>> s = '{foo: 8}'
>>> yaml.load(s)
{'foo': 8}
like image 193
RanRag Avatar answered Nov 17 '22 17:11

RanRag


You can try demjson.

>>> import demjson
>>> demjson.decode('{foo:3}')
{u'foo': 3}
like image 33
null Avatar answered Nov 17 '22 16:11

null


No, this is not possible. To successfully parse that using simplejson you would first need to transform it into a valid JSON string.

Depending on how strict the format of your incoming string is this could be pretty simple or extremely complex.

For a simple case, if you will always have a JSON object that only has letters and underscores in keys (without quotes) and integers as values, you could use the following to transform it into valid JSON:

import re
your_string = re.sub(r'([a-zA-Z_]+)', r'"\1"', your_string)

For example:

>>> re.sub(r'([a-zA-Z_]+)', r'"\1"', '{foo:3, bar:4}')
'{"foo":3, "bar":4}'
like image 1
Andrew Clark Avatar answered Nov 17 '22 16:11

Andrew Clark