我需要帮助来显示结果编号 2,下面是结果编号 1 的完整代码
import json
json_obj = {
"STATUS": "SUCCESS",
"DATA": {
"data": [
{
"destinationId": "216",
"name": "Bandung",
"destinationCode": "24417",
"tourList": []
},
{
"destinationId": "54",
"name": "Batam",
"destinationCode": "BTH",
"tourList": [
{
"tourId": "20586",
"tourCode": "IDBTH00585",
"tourName": "BATAM SPECIAL SPA PACKAGE",
"tourTime": [
{
"tourStartTime": "09:00:00",
"tourEndTime": "16:00:00",
}
],
"pricing": [
{
"adultPrice": "193.00",
"tourId": "20586"
}
]
}
]
}
]
}
}
wanted = ['tourId', 'tourCode', 'tourName', 'tourTime','pricing']
for item in json_obj["DATA"]["data"]:
details = item['tourList']
if not details:
pass
else:
#print(details['tourId'])
for d in details:
for key in wanted:
print(key, ':', json.dumps(d[key], indent=4))
#Put a blank line at the end of the details for each item
print()
结果数 1结果
如何编辑代码,使结果像结果编号 2,只是让它变得像结果编号 2 一样好读
结果数 2
tourId : "20586"
tourCode : "IDBTH00585"
tourName : "BATAM SPECIAL SPA PACKAGE"
tourStartTime: "09:00:00"
tourEndTime: "16:00:00"
adultPrice: "193.00"
tourId: "20586"
还有 1 个问题,我可以将 JSON 值的名称编辑成我们自己的字符串吗例子(tourId : "20586"( 到 (Tour ID : 20586(
2 个问题(仅使用 1(的一种方法是更改wanted
并包含一个新rewriteDic
以将键替换为其他值。对于dict()
wanted
的部分,我们自行处理打印。隐式格式是采用子项列表的集合,在这种情况下只会打印子项。这是根据给定的 JSON 量身定制的,在使用前使用其他输出进行测试并相应地进行调整。如果我们遇到rewriteDic
内部给出的键,我们使用那里的值进行打印,而不是"真正的"键:
注释代码以解释正在执行的操作:
wanted = ['tourId', 'tourCode', 'tourName',
{'tourTime':['tourStartTime','tourEndTime']}, # if we encounter a dict we change
{'pricing':['adultPrice','tourId']} # the printing mechanics
]
rewriteDic = {'tourId':'Tour ID', 'tourCode':'Super Douper Cool and Secret ID Code'}
for item in json_obj["DATA"]["data"]:
details = item['tourList']
if not details:
pass
else:
#print(details['tourId'])
for d in details:
for key in wanted:
if isinstance(key, dict): # got a dict, so our "wanted" contains the real
for sub in key: # subkeys as list as value inside the dict
subKeys = key[sub] # this is what we want to print
for sKey in subKeys: # so for all that are in
# ask rewriteDic for the value of sKey, else use sKey
print( rewriteDic.get(sKey,sKey),":",d[sub][0][sKey])
else:
# Edit: apply rewriteDic here too:
# print(key, ':', json.dumps(d[key], indent=4))
print(rewriteDic.get(key,key),':',d[key])
# Put a blank line at the end of the details for each item
print()
输出:
Tour ID : 20586
Super Douper Cool and Secret ID Code : IDBTH00585
tourName : BATAM SPECIAL SPA PACKAGE
tourStartTime : 09:00:00
tourEndTime : 16:00:00
adultPrice : 193.00
Tour ID : 20586