如何用Python解析有点错误的JSON? [英] How to parse somewhat wrong JSON with Python?

查看:153
本文介绍了如何用Python解析有点错误的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自外部输入源的以下JSON字符串:

  {value:82363549923gnyh49c9djl239pjm01223,id:17893} 

这是错误格式的JSON字符串(id和value必须用引号引起来),但我仍然需要解析它。我曾尝试simplejson和json-py,似乎他们不能设置解析这样的字符串。

我在Google App引擎上运行Python 2.5,所以任何C-基于浏览器的解决方案,如python-cjson不适用。

输入格式可以更改为XML或YAML,除了上面列出的JSON,但我在项目中使用JSON并在特定的地方改变格式不会很好。



现在我已经切换到XML并成功解析数据,但期待任何解决方案让我因为YAML(> = 1.2)是JSON的一个超集,所以你可以这样做:

p>

 >>> import yaml 
>>> s ='{value:82363549923gnyh49c9djl239pjm01223,id:17893}'
>>> yaml.load(s)
{'id':17893,'value':'82363549923gnyh49c9djl239pjm01223'}


I have a following JSON string coming from external input source:

{value: "82363549923gnyh49c9djl239pjm01223", id: 17893}

This is wrong-formatted JSON string ("id" and "value" must be in quotes), but I need to parse it anyway. I have tried simplejson and json-py and seems they could not be set up to parse such strings.

I am running Python 2.5 on Google App engine, so any C-based solutions like python-cjson are not applicable.

Input format could be changed to XML or YAML, in adition to JSON listed above, but I am using JSON within the project and changing format in specific place would not be very good.

Now I've switched to XML and parsing the data successfully, but looking forward to any solution that would allow me to switch back to JSON.

解决方案

since YAML (>=1.2) is a superset of JSON, you can do:

>>> import yaml
>>> s = '{value: "82363549923gnyh49c9djl239pjm01223", id: 17893}'
>>> yaml.load(s)
{'id': 17893, 'value': '82363549923gnyh49c9djl239pjm01223'}

这篇关于如何用Python解析有点错误的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆