-1

I'm expecting a JSON msg to be parsed with Python along these lines to come in through MQTT:

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

Depending on the circumstances, these options may or may not be parsed through Python into the JSON msg, and as such, it may end up looking as:

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

And thus skipping OPTION2 and it's value entirely.

To avoid my script borking out on my, I was thinking of scanning if the option is there first, before setting it, like so:

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

However, this doesn't seem to work, it comes up with:

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

Any help would be really appreciated! Thanks.

user5740843
  • 1,540
  • 5
  • 22
  • 42

2 Answers2

2

If you are working with if else pass, continue is used with loops:-

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

Continue is used with loops. Also you can try:-

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


for dataItem in data:
   if "OPTION2" == dataItem:
      continue
   >do something< 
Rakesh Kumar
  • 4,319
  • 2
  • 17
  • 30
0

continue is used with loops, you might need passehere. Also, you can use in to check if a key is available in a dictionary:

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

But I don't think, that is what you want! You want to have your default values and fill in the blanks if the key is not available in data:

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

Find out more here.

Community
  • 1
  • 1
Yan Foto
  • 10,850
  • 6
  • 57
  • 88
  • Your first option seems to give me a syntax error: else: ^ SyntaxError: invalid syntax – user5740843 Aug 16 '16 at 08:24
  • yes because instead of `#` you have to have some statements. Replace it for test purposes with `pass` and the error is gone. – Yan Foto Aug 16 '16 at 08:25
  • I have added my statement in between the if and the else. I did not take your code example literally. – user5740843 Aug 16 '16 at 08:27
  • I just loaded your example data with `json.loads` and ran the abovementioned code. No syntax error, whatsoever. Which part isn't working for you? – Yan Foto Aug 16 '16 at 08:29
  • I too have added my example with: data = json.loads(msg.payload), I have then used your if 'OPTION1' in data: *my statement* else: pass but it still gives me a syntax error on else: - i have no idea why. – user5740843 Aug 16 '16 at 08:31
  • I cannot possibly say why and which syntax error you're getting. to verify, you can just write e.g. `'OPTION2' in data` in your python console and see the results. However, I still think the second solution (with `update`) is what you should use *if* you only want to update default values. – Yan Foto Aug 16 '16 at 08:34