将数组附加到json python

时间:2017-12-14 20:30:14

标签: python arrays json

我在python3上处理JSON并且我想在json对象中附加一个数组,这是我到目前为止的代码:

values = [20.8, 21.2, 22.4] 
timeStamps = ["2013/25/11 12:23:20", "2013/25/11 12:25:20", "2013/25/11 12:28:20"] 

myJSON = '{ Gateway: {"serial":"1001", "status":"ok"},
 "Tag":{"TID":"FF01", "EPC":"EE01"},
 "DataSet":{"sensorType":"temperature", "values":[], "timeStamps":[] } }'

有没有简单的方法来附加数组而不必将它们转换为字符串并以纯文本形式插入?

提前致谢,

3 个答案:

答案 0 :(得分:3)

Python通过myJSON_d = json.loads(myJSON) myJSON_d.['DataSet'].update({'values': values, 'timeStamps': timeStamps}) myJSON = json.dumps(myJSON_d) 模块包含SimpleJSON。用它来序列化/反序列化JSON字符串和python dicts:

element.getAttribute("innerHTML")

答案 1 :(得分:2)

您可以使用json.dumps解析JSON,进行操作,然后通过import json values = [20.8, 21.2, 22.4] timeStamps = ["2013/25/11 12:23:20", "2013/25/11 12:25:20", "2013/25/11 12:28:20"] myJSON = '{ "Gateway": {"serial":"1001", "status":"ok"}, "Tag":{"TID":"FF01", "EPC":"EE01"}, "DataSet":{"sensorType":"temperature", "values":[], "timeStamps":[] } }' o = json.loads(myJSON) o["DataSet"]["values"] = values o["DataSet"]["timeStamps"] = timeStamps newJSON = json.dumps(o) print(newJSON) # Output: # {"Gateway": {"serial": "1001", "status": "ok"}, "Tag": {"TID": "FF01", "EPC": "EE01"}, "DataSet": {"sensorType": "temperature", "values": [20.8, 21.2, 22.4], "timeStamps": ["2013/25/11 12:23:20", "2013/25/11 12:25:20", "2013/25/11 12:28:20"]}} 转换回JSON。

请注意,我必须编辑您的JSON才能使其有效。 (" Gateway"错过了封闭的双引号。)

json

答案 2 :(得分:2)

看起来你也在尝试构建json。在这种情况下,你应该这样做:

import json

values = [20.8, 21.2, 22.4] 
timeStamps = ["2013/25/11 12:23:20", "2013/25/11 12:25:20", "2013/25/11 12:28:20"] 

d = dict(Gateway= dict(serial="1001", status="ok"),
     Tag= dict(TID="FF01", EPC= "EE01"),
     DataSet= dict(sensorType="temperature",values=values,timeStamps=timeStamps))

print(json.dumps(d,indent =2))

返回:

{
  "DataSet": {
    "timeStamps": [
      "2013/25/11 12:23:20",
      "2013/25/11 12:25:20",
      "2013/25/11 12:28:20"
    ],
    "values": [
      20.8,
      21.2,
      22.4
    ],
    "sensorType": "temperature"
  },
  "Tag": {
    "TID": "FF01",
    "EPC": "EE01"
  },
  "Gateway": {
    "serial": "1001",
    "status": "ok"
  }
}