本次的应用场景是将json数据转换成字典,再将字典遍历打印出来,json数据保存在json.txt文件中:
[root@nginx python]# cat json.txt
{"eventType":"MessageCreated","payload":{"content":"@zhangsan","dialogId":"G-888999","messageId":835,"replyTo":0,"sender":{"enigmaId":"zhangsan","id":789999,"name":"张三"},"timestamp":1605512370081,"type":"text"},"timestamp":1605512370081}
[root@nginx python]#
下面用两种方式将这个json数据按照键值对的形式打印出来。
方法一:json.py
import json
with open("json.txt") as jsdata:
contents = json.loads(jsdata.read())
def list_dict(dic1):
if isinstance(dic1, dict):
for i in range(len(dic1)):
temp_key = dic1.keys()[i]
temp_value = dic1[temp_key]
if isinstance(temp_value, dict):
list_dict(temp_value)
else:
print"%s:%s" %(temp_key,temp_value)
list_dict(contents)
方法二:json2.py
import json
with open("json.txt") as jsdata:
contents = json.loads(jsdata.read())
def list_dict2(dic1):
if isinstance(dic1, dict):
for key,value in dic1.items():
if isinstance(value, dict):
list_dict2(value)
else:
print"%s:%s" %(key,value)
list_dict2(contents)
输出的效果:
[root@nginx python]# python json.py
eventType:MessageCreated
enigmaId:zhangsan
id:789999
name:张三
dialogId:G-888999
replyTo:0
timestamp:1605512370081
content:@zhangsan
messageId:835
type:text
timestamp:1605512370081
[root@nginx python]#