在Python中,如何通过删除方括号和花括号来打印Json [英] In Python, how to print Json by removing brackets and braces
问题描述
我想以一种不错的方式打印Json,我想摆脱括号,引号和花括号,而仅使用缩进和行尾来显示json的结构。
I want to print the Json in a nice way, I want to get rid of the brackets, quotes and braces and only use indents and line-endings to show the json's structure.
例如,如果我有这样的Json:
for example if I have a Json like this:
{
"A": {
"A1": 1,
"A2": 2
},
"B": {
"B1": {
"B11": {
"B111": 1,
"B112": 2
},
"B12": {
"B121": 1,
"B122": 2
}
},
"B2": {
"B21": [1,2],
"B22": [1,2]
}
},
"C": "CC"
}
我如何通过删除{}和[]来打印json,我想要的是:
How could I print the json by removing {} and [], what I want is:
A:
A1: 1
A2: 2
B:
B1:
B11:
B111: 1
B112: 2
B12:
B121: 1
B122: 2
B2:
B21: 1, 2
B22: 1, 2
C: CC
推荐答案
您可以将json加载到python对象中,然后将python对象转换为YAML。另一个解决方案是简单地遍历字典并根据需要对其进行格式化。
You can load the json into a python object, and then convert the python object to YAML. The other solution is to simply iterate over the dictionaries and format it however you want.
这里有一个将其转换为YAML的示例。它不能完全满足您的需求,但是非常接近。有很多方法可以自定义输出,这只是一个简单的技巧,可以显示一般的想法:
Here's an example of converting it to YAML. It doesn't give you precisely what you want, but it's pretty close. There are lots of ways to customize the output, this is just a quick hack to show the general idea:
import json
import yaml
data = json.loads('''
{
"A": {
"A1": 1,
"A2": 2
},
"B": {
"B1": {
"B11": {
"B111": 1,
"B112": 2
},
"B12": {
"B121": 1,
"B122": 2
}
},
"B2": {
"B21": [1,2],
"B22": [1,2]
}
},
"C": "CC"
}
''')
print yaml.safe_dump(data, allow_unicode=True, default_flow_style=False)
这是我得到的输出:
A:
A1: 1
A2: 2
B:
B1:
B11:
B111: 1
B112: 2
B12:
B121: 1
B122: 2
B2:
B21:
- 1
- 2
B22:
- 1
- 2
C: CC
这篇关于在Python中,如何通过删除方括号和花括号来打印Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!