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])
由于json_dictionary
在函数内部,因此会出现错误。您需要返回或声明json_dictioanry
,然后调用函数on_message
。尝试这种方式:
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])