我想使用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"
然而,它非常丑陋。有更简洁的方式吗?
答案 0 :(得分:2)
考虑这样的事情,你可以使用"指定一个子项。"划分你的钥匙。这是一个例子:
KEYS_TO_EXPORT = ["id", "dateTime", "title", "channel.title"]
item = {"id": 1, "channel": {"title": "nailed_it"}}
this_row = []
for export_key in KEYS_TO_EXPORT:
try:
value = item
for key in export_key.split("."):
value = value[key]
this_row.append(str(value).encode('utf-8'))
except KeyError:
this_row.append("")
编辑以使用列表:
根据对原始问题的编辑,可以轻松扩展此解决方案以使用项目列表,如下所示。此外,我转而使用.get
,就像评论中建议的那样。
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"}},
{"id": 3}
]}
this_row = []
for item in my_data["items"]:
for export_key in KEYS_TO_PRINT:
value = item
for key in export_key.split("."):
value = value.get(key)
if value == None: break
this_row.append(str(value).encode('utf-8') if value != None else "")
print this_row