2016-08-16 85 views
-1

我期待一個JSON味精變量與Python沿着這些線路進行解析,通過MQTT進來:的Python尋找在JSON

{"OPTION1": "0", "OPTION2": "50", "OPTION3": "0", "OPTION4": "0"} 

根據情況的不同,這些選項可能會或可能不會進行解析通過的Python進入JSON MSG,正因爲如此,它可能最終尋找爲:

{"OPTION1": "0", "OPTION3": "0", "OPTION4": "0"} 

並且因此跳過OPTION2和它完全值。

爲了避免我的腳本borking了我,我就在想掃描如果選項是那裏第一次,在設置前,像這樣:

 if data['OPTION1']: 
       >do something here< 
     else: 
       continue 

然而,這似乎並沒有工作,它想出:

File "listen-mqtt.py", line 28 
    continue 
SyntaxError: 'continue' not properly in loop 

任何幫助將非常感激!謝謝。

+1

'pass'就是你要找的(不是'繼續') –

+0

'else'子句是不必要的。 https://docs.python.org/3/tutorial/controlflow.html?highlight=continue – tanglong

回答

2

如果您正在使用的if else 繼續使用與循環工作: -

if data['OPTION1']: 
    >do something here< 
else: 
    pass 

繼續與循環使用。你也可以嘗試: -

for dataItem in data: 
    if "OPTION2" == dataItem: 
     pass 
    else: 
    >do something< 


for dataItem in data: 
    if "OPTION2" == dataItem: 
     continue 
    >do something< 
0

continue與循環使用的,您可能需要pass ehere。此外,您還可以使用in檢查的關鍵是提供一本字典:

if 'OPTION1' in data: 
    # do something 
else: 
    pass 

但我不認爲,這是你想要的!您希望您的默認值,填補空白,如果關鍵是不具備的data

defaults = {"OPTION1": "0", "OPTION2": "50", "OPTION3": "0", "OPTION4": "0"} 
finalData = defaults.update(data) 

瞭解更多here

+0

你的第一個選擇似乎給了我一個語法錯誤:else: ^ SyntaxError:無效的語法 – user5740843

+0

是的,因爲而不是'#'你必須有一些陳述。用'pass'替換它以用於測試目的,並且錯誤消失。 –

+0

我在if和else之間添加了我的聲明。我沒有從字面上理解你的代碼示例。 – user5740843