'for data in json_dictionary: # Loop through dictionary keys NameError: name 'json_dictionary' is not defined
def on_message(client, userdata, msg): # The callback for when a message is received from the server.
json_string = str(msg.payload)
json_dictionary = json.loads(json_string) # Load JSON string to a dictionary
for data in json_dictionary: # Loop through dictionary keys
print(data, ":", json_dictionary[data])
Solution 1:[1]
It gives an error as json_dictionary is inside the function. You need to either return or declare json_dictioanry and then call the function on_message.
Try in this way:
def on_message(client, userdata, msg): # The callback for when a message is received from the server.
json_string = str(msg.payload)
json_dictionary = json.loads(json_string) # Load JSON string to a dictionary
return json_dictionary
json_dictionary = on_message(client,userdata,msg)
for data in json_dictionary.keys():
print(data, ":", json_dictionary[data])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SAI SANTOSH CHIRAG |
