2016-02-03 42 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