【问题标题】:Crunching json with python用python处理json
【发布时间】:2010-11-05 14:36:21
【问题描述】:

呼应我的other question 现在需要找到一种方法将 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 的快速响应!

【问题讨论】:

  • 您使用的 Python 版本在这里有些相关。自(我认为)2.6 以来,json 一直是标准库的一部分
  • 使用 python 2.6,所以建议的解决方案对我很有效

标签: python json parsing


【解决方案1】:

在 Python 2.6 中:

import json
print json.loads( json_string )

基本上,当你使用 json 模块解析 json 时,你会得到一个 Python dict。如果您只是打印一个 dict 和/或将其转换为一个字符串,它将全部在一行上。当然,在某些情况下,Python dict 会与 json 编码的字符串略有不同(例如带有布尔值和空值),所以如果这很重要,那么你可以说

import json
print json.dumps( json.loads(json_string) )

如果您没有 Python 2.6,那么您可以使用 the simplejson module。在这种情况下,您只需说

import simplejson
print simplejson.loads( json_string )

【讨论】:

  • 只打印 json.loads 将打印数据的 Python 表示,而不是 JSON 编码的。
【解决方案2】:

http://docs.python.org/library/json.html

>>> 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"}}}'

【讨论】:

  • 哦,我差点忘了...你应该使用 (',', ':') 作为 json.dumps 的 separators 参数(参见文档)。这将使数据更加紧凑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-06
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
相关资源
最近更新 更多