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

查看:29
本文介绍了如何用 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 并成功解析了数据,但期待任何可以让我切换回 JSON 的解决方案.

解决方案

由于 YAML (>=1.2) 是 JSON 的超集,您可以这样做:

<预><代码>>>>导入 yaml>>>s = '{值:82363549923gnyh49c9djl239pjm01223",ID:17893}'>>>yaml.load(s){'id':17893,'值':'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天全站免登陆