2016-02-03 44 views
1

我想使用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" 

然而,这是很丑陋的。有没有更好的方法?

+0

您可以添加您正在使用的JSON文件(或子集)吗?预期的产出? – Brian

+0

你想做什么不清楚。你说“但是我有'子'(?)”,你想发生什么?示例输入和输出可能是有用的...... – martineau

+0

我知道这与问题无关,但看看item.get()语法,它会为您节省一个尝试/除了 – Will

回答

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,像Will在评论中所建议的那样。

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 
+0

这似乎并不适用于我:KEYS_TO_EXPORT = [“channel.title”] item = {“id” :1,“channel”:{id:“channelid1”,“title”:“nailed_it1”},“id”:2,“channel”:{id:“channelid2”,“title”:“nailed_it2”}} this_row = [] 为export_key在KEYS_TO_EXPORT: 尝试: 值=项 在export_key.split( “”)键: 值=值[键] this_row.append(STR(值).encode(” utf-8')) print this_row (KeyError除外): this_row.append(“”) – Chris

+0

如果您希望它打印“nailed_it1”和“nai led_it2“,它当然不能。您传递它的字典格式不正确,字典中的所有密钥都必须是唯一的。对于单个键不可能有两个值,因此您为键定义的第二个值是被使用的值,这就是为什么这只打印“nailed_it2”。 –

+0

请参阅修改示例;你是对的,我最初的例子并不好。 – Chris