[英]Python: create dictionary inside dictionary to convert to JSON
我想創建JSON:
[
{
measurement: "Equipment1",
fields: {
Pressure: 5.5
},
tags:{
MachineType:"type1"
},
timestamp: 1530717056.48
}
]
我寫的代碼是:
import json
import time
from decimal import Decimal
count = 0
read_pressures = []
while (count < 100):
current_time=time.time()
array_of_pressures.append(dict(measurement="Equipment1", dict(pressure=5.5),dict(MachineType="Type1"),timestamp=time.time()))
time.sleep(0.01)
count = count + 1
print(data) #
read_pressures.append(data)
print ("printing all values")
print(json.dumps(read_pressures, ensure_ascii=False))
#print(read_pressures)
代碼給出錯誤“ SyntaxError:在關鍵字arg之后為非關鍵字arg”,但我不知道如何在字典中創建字典。 任何幫助表示贊賞嗎?
謝謝
dict(measurement="Equipment1", dict(pressure=5.5),dict(MachineType="Type1"),timestamp=time.time()))
在這里,您缺少某些詞典值的鍵名(“字段”和“標簽”)。
dict(measurement="Equipment1", fields=dict(pressure=5.5), tags=dict(MachineType="Type1"), timestamp=time.time()))
或者您可以更簡單地將其編寫為
data = { "measurement": "Equipment1",
"fields": { "pressure": 5.5 },
"tags": { "MachineType": "Type1" },
"timestamp": time.time()
}
正如tobias_k指出的那樣,您似乎還試圖將dict追加到名為array_of_pressures
,該代碼不會在代碼的任何地方創建,而不是簡單地將dict分配給data
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.