用 python 处理 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1039877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:20:22  来源:igfitidea点击:

Crunching json with python

pythonjsonparsing

提问by Sergey Golovchenko

Echoing my other questionnow need to find a way to crunch json down to one line: e.g.

回应我的另一个问题现在需要找到一种方法将 json 压缩到一行:例如

{"node0":{
    "node1":{
        "attr0":"foo",
        "attr1":"foo bar",
        "attr2":"value with        long        spaces"
    }
}}

would like to crunch down to a single line:

想压缩到一行:

{"node0":{"node1":{"attr0":"foo","attr1":"foo bar","attr2":"value with        long        spaces"}}}

by removing insignificant white spaces and preserving the ones that are within the value. Is there a library to do this in python?

通过删除无关紧要的空格并保留值内的空格。是否有一个库可以在 python 中执行此操作?

EDITThank you both drdaeman and Eli Courtwright for super quick response!

编辑感谢 drdaeman 和 Eli Courtwright 的超级快速响应!

回答by drdaeman

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

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

回答by Eli Courtwright

In Python 2.6:

在 Python 2.6 中:

import json
print json.loads( json_string )

Basically, when you use the json module to parse json, then you get a Python dict. If you simply print a dict and/or convert it to a string, it'll all be on one line. Of course, in some cases the Python dict will be slightly different than the json-encoded string (such as with booleans and nulls), so if this matters then you can say

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

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

If you don't have Python 2.6 then you can use the simplejson module. In this case you'd simply say

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

import simplejson
print simplejson.loads( json_string )