在 Python 中解码复杂的 JSON
我在 PHP 中创建了一个 JSON 对象,该 JSON 对象在其中一个单元格中包含另一个转义的 JSON 字符串:
php > $insidejson = array('foo' => 'bar','foo1' => 'bar1'); php > $arr = array('a' => array('a1'=>json_encode($insidejson))); php > echo json_encode($arr); {"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}
然后,使用 Python,我尝试使用 simplejson 对其进行解码:
>>> import simplejson as json >>> json.loads('{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}')
这失败并出现以下错误:
Traceback (most recent call last): File "", line 1, in ? File "build/bdist.linux-i686/egg/simplejson/__init__.py", line 307, in loads File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 335, in decode File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 351, in raw_decode ValueError: Expecting , delimiter: line 1 column 14 (char 14)
如何解码此 JSON 对象在Python中? PHP 和 JS 都成功解码它,我无法更改它的结构,因为这需要对不同语言的许多不同组件进行重大更改。
谢谢!
I have a JSON object created in PHP, that JSON object contains another escaped JSON string in one of it's cells:
php > $insidejson = array('foo' => 'bar','foo1' => 'bar1'); php > $arr = array('a' => array('a1'=>json_encode($insidejson))); php > echo json_encode($arr); {"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}
Then, with Python, I try deocding it using simplejson:
>>> import simplejson as json >>> json.loads('{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}')
This fails with the following error:
Traceback (most recent call last): File "", line 1, in ? File "build/bdist.linux-i686/egg/simplejson/__init__.py", line 307, in loads File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 335, in decode File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 351, in raw_decode ValueError: Expecting , delimiter: line 1 column 14 (char 14)
How can I get this JSON object decoded in Python? Both PHP and JS decode it successfully and I can't change it's structure since that would require major changes in many different components in different languages.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试在字符串前加上“r”前缀,使其成为原始字符串:
Alex 下面所说的是正确的:您可以将斜杠加倍。 (当我开始我的回答时,他的答案还没有发布。)我认为使用原始字符串更简单,因为它是一种语言功能,意味着同样的事情,而且更难出错。
Try prefixing your string with 'r' to make it a raw string:
What Alex says below is true: you can just double the slashes. (His answer was not posted when I started mine.) I think that using raw strings is simpler, if only because it's a language feature that means the same thing and it's harder to get wrong.
尝试
也许 simplejson 太“简单”了。
Try
Maybe simplejson is too much "simple".
如果您想将反斜杠插入字符串中,它们需要自行转义。
我已经测试过它,Python 可以很好地处理该输入 - 除非我使用了标准库中包含的 json 模块(
import json
,Python 3.1)。If you want to insert backslashes into a string they need escaping themselves.
I've tested it and Python handles that input just fine - except I used the json module included in the standard library (
import json
, Python 3.1).