我正在尝试将此JSON文本格式化为易于阅读的格式,并且出现了一些错误。
"extra":[" ",{"color":"dark_red","text":"- "},{"color":"red","text":"Released today @ 3PM EST"}],"text":""}{"text":""}{"extra":[{"bold":true,"color":"gold","text":"Battle Pass: "},{"color":"gray","text":"You do not have premium "},{"color":"gold","text":"Pass"},{"color":"gray","text":"."}],"text":""}{"extra":[{"color":"gray","text":"You can buy this at anytime and receive premium rewards."}],"text":""}{"extra":[{"color":"gray","text":"Purchase a "},{"color":"gold","text":"Pass "},{"color":"gray","text":"copy: "},{"underlined":true,"color":"white","clickEvent":{"action":"open_url","value":"http://store.example.net"},"text":"store.example.net"},{"color":"gold","text":" [50% Off]"}],"text":""}{"text":""}
我将此保存为变量msg
。由于它只是我感兴趣的'text'
,因此我尝试做print(msg['text'])
,但这没有用。我应该将其拆分为列表,然后以这种方式处理吗?还是有一种非常简单的方法来处理我不熟悉的JSON库?
答案 0 :(得分:3)
如果您拥有有效的json
文件或字符串,则使其更易于阅读的一种方法是使用indent
关键字参数,例如
import json
d = {i: str(i) for i in range(10)}
s = json.dumps(d)
print(s)
# {"0": "0", "1": "1", "2": "2", "3": "3", "4": "4", "5": "5", "6": "6", "7": "7", "8": "8", "9": "9"}
ss = json.dumps(json.loads(s), indent=4)
print(ss)
# {
# "0": "0",
# "1": "1",
# "2": "2",
# "3": "3",
# "4": "4",
# "5": "5",
# "6": "6",
# "7": "7",
# "8": "8",
# "9": "9"
# }