用Python解析JSON
我之前在另一个问题中提到过,现在我需要找到一种方法,把json压缩成一行,比如:
{"node0":{
"node1":{
"attr0":"foo",
"attr1":"foo bar",
"attr2":"value with long spaces"
}
}}
我想把它压缩成一行:
{"node0":{"node1":{"attr0":"foo","attr1":"foo bar","attr2":"value with long spaces"}}}
通过去掉不重要的空格,同时保留值里面的空格。有没有什么库可以在python中做到这一点?
编辑 感谢drdaeman和Eli Courtwright的快速回复!
2 个回答
2
在 Python 2.6 中:
import json
print json.loads( json_string )
简单来说,当你使用 json 模块来解析 json 数据时,你会得到一个 Python 字典。如果你直接打印这个字典或者把它转换成字符串,它会全部显示在一行上。当然,在某些情况下,Python 字典和 json 编码的字符串会有些不同(比如布尔值和空值),所以如果这很重要的话,你可以这样做:
import json
print json.dumps( json.loads(json_string) )
如果你没有 Python 2.6,那么你可以使用 simplejson 模块。在这种情况下,你只需要这样做:
import simplejson
print simplejson.loads( json_string )
21
这是一个链接,指向Python的官方文档,专门讲解如何使用JSON(JavaScript对象表示法)。JSON是一种常用的数据格式,常用于在不同的系统之间传输数据。你可以通过这个链接了解更多关于JSON的内容和如何在Python中使用它。
>>> import json
>>> json.dumps(json.loads("""
... {"node0":{
... "node1":{
... "attr0":"foo",
... "attr1":"foo bar",
... "attr2":"value with long spaces"
... }
... }}
... """))
'{"node0": {"node1": {"attr2": "value with long spaces", "attr0": "foo", "attr1": "foo bar"}}}'