我想使用Python遍历JSON文件并打印一组键。如何序列化Python列表中的JSON密钥?
例如:
import json
KEYS_TO_PRINT = ["id", "channel.title"]
my_data = {"items": [{"id": 1, "channel": {"channelid": "channelid1", "title": "nailed_it1"}}, {"id": 2, "channel": {"channelid": "channelid2", "title": "nailed_it2"}}]}
this_row = []
for item in my_data["items"]:
for key in KEYS_TO_PRINT:
try:
if "." in key:
split_up = key.split(".")
print item[split_up[0]][split_up[1]]
else:
print item[key]
except KeyError:
print "Oops"
然而,这是很丑陋的。有没有更好的方法?
您可以添加您正在使用的JSON文件(或子集)吗?预期的产出? – Brian
你想做什么不清楚。你说“但是我有'子'(?)”,你想发生什么?示例输入和输出可能是有用的...... – martineau
我知道这与问题无关,但看看item.get()语法,它会为您节省一个尝试/除了 – Will