Is there any way to make simplejson less strict?

泄露秘密 提交于 2019-11-30 20:52:53

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}

You can try demjson.

>>> import demjson
>>> demjson.decode('{foo:3}')
{u'foo': 3}

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}'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!