![](/img/trans.png)
[英]using Python Trying to Increment the JSON object values in a Array before copying the object in a array in a new file
[英]Increment json values using Python
我正在開發一個MQTT客戶端,該客戶端將發布到主題“城市/地方”,並將json對象格式的數據發送到MQTT代理。
我對結構數據有誤解。
我的json對象看起來像這樣:
people = {'man': 31, 'women': 31, 'date': 23/11/15, 'city': "Moscu"}
由於某種原因,我需要每秒增加加入Moscu的人數。
這是我的完整代碼:
import paho.mqtt.client as mqtt
import json
import time
mqttc = mqtt.Client('python_publisher')
mqttc.connect('127.0.0.1', 1883)
people = {'man': 31, 'women': 31, 'date': 23/11/15, 'city': "Moscu"}
while True:
people_json2str = json.dumps(people)
print (people_json2str)
mqttc.publish('city/place', people_json2str)
people = {'man': 31 + 1, 'women': 31 + 1, 'date': 23/11/15, 'city': "Moscu"}
time.sleep (1)
我將json解析為字符串格式,因為mqtt需要這樣的數據。 然后,我將其發布到主題“城市/地方”。 之后,我嘗試增加json對象的值,但它不能那樣工作。 您現在是否可以使用Python更新json值並將其解析為字符串?
這個
people = {'man': 31, 'women': 31, 'date': 23/11/15, 'city': "Moscu"}
是一本字典 。
您可以通過字典鍵訪問字典中的值:
>>> print people['man']
>>> 31
您還可以更改字典值,就像更改變量一樣。
要使x=1
遞增,請執行x+=1
。 類似地,您會
people['man'] +=1
將整數“ man”增加一。 婦女也是如此。
順便說一句,我很驚訝地看到23/11/15
沒有引號(這會使它成為字符串)。 您寫的是23 divided by 11 divided by 15
。 那肯定不是你想要的:D
這個
people = {'man': 31 + 1, 'women': 31 + 1, 'date': '23/11/15', 'city': "Moscu"}
每秒創建一個新的詞典,其中man
和woman
設置為32
而不是增加您顯然想執行的最后一個值。
您需要查看如何訪問python詞典
import paho.mqtt.client as mqtt
import json
import time
mqttc = mqtt.Client('python_publisher')
mqttc.connect('127.0.0.1', 1883)
people = {'man': 31, 'women': 31, 'date': 23/11/15, 'city': "Moscu"}
while True:
people_json2str = json.dumps(people)
print (people_json2str)
mqttc.publish('city/place', people_json2str)
people['man'] = people['man'] + 1
people['women'] = people['woman'] + 1
time.sleep (1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.