2017-02-10 74 views
1

我想知道您是否可以用我目前正在處理的一段代碼來幫助我。我是Python新手,這是我嘗試編寫的第一個主要腳本之一。Python(DICT) - 使用JSON填充 - 不能在請求中使用變量

import json, sys 
from pprint import pprint 
#Importing workbench json output into the python script. 
with open('jsonoutput.json') as data_file: 
    data = json.load(data_file) 

#Sets the verible for the while loop. 
x = int(0) 

while x <= 1: 
    y = x 
    print type(data) 
    jdata = data["result"]["items"][y]["tagValues"]["IdDevicesMap"]["value"] 
    if setup_1(jdata) == True: 
     Default_1 += 1 
    else: 
     print "exiting" 

錯誤我得到當它運行:

Traceback (most recent call last): 
    File "main.py", line 47, in <module> 
    jdata = data["result"]["items"][y]["tagValues"]["IdDevicesMap"]["value"] 
KeyError: 'tagValues' 
只需在一個側面說明

爲好,當我手動把列表中的號碼[Y] 1代碼運行完美。所以它就像我在輸入變量[y]到請求中的方式一樣。

+0

好像tagValues是不是在一些你從文件中讀取嵌套字典。介意提供輸入? –

回答

1

我很確定你讀的json在每一個沒有tagValues。你可能會想嘗試try:和except:

import json, sys 
from pprint import pprint 
#Importing workbench json output into the python script. 
with open('jsonoutput.json') as data_file: 
    data = json.load(data_file) 
x = 0 
while True: 
    try: 
     jdata = data["result"]["items"][x]["tagValues"]["IdDevicesMap"]["value"] 
     if setup_1(jdata) == True: 
      Default_1 += 1 
     else: 
      print "exiting" 
      break 
    except KeyError: 
     print data["result"]["items"][x] 
     pass 
    x+=1 

要在Python的方式做到這一點:

import json, sys 
from pprint import pprint 
#Importing workbench json output into the python script. 
with open('jsonoutput.json') as data_file: 
    data = json.load(data_file) 

for x, d in enumerate(data["result"]["items"]): #in case you need a counter 
    try: 
     jdata = d["tagValues"]["IdDevicesMap"]["value"] 
     if setup_1(jdata) == True: 
      Default_1 += 1 
     else: 
      print "exiting" 
      break 
    except KeyError: 
     pass 
+0

Ahh真棒,這正是發生了什麼,出於某種原因,我自動假定每個設備都有一個tagValue,這是不正確的。改變了我的代碼來處理這個異常,它工作得很好。 –

1

此錯誤僅表示您沒有名爲"tagValues"的密鑰。這將工作,如果你的json看起來像這樣。

data = {"result": 
     {"items": 
      [ {"tagValues": 
       {"IdDevicesMap": 
        {"value": 
        { 
         #data 
        } 
        } 
       } 
       } 
      ] 
     } 
     } 

所以,要麼你的數據不會這個樣子,或者如果確實如此,那麼所謂的"tagValues"密鑰丟失。

另一件事是告訴如果數據[「結果」] [「項目」]列表或JSON?

+0

哦。謝謝。將修復。 – Pbd

+0

再次感謝。唷。 – Pbd