简体   繁体   中英

append an array to a json python

I'm dealing with JSON on python3 and I want to append an array into a json object, this is my code so far:

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":[] } }'

Is there any easy way to append the arrays without having to cast them to string and inserted as plain text ?

Thanks in advance,

Python includes SimpleJSON via the json module. Use it to serialize/de-serialize from JSON strings and python dicts:

myJSON_d = json.loads(myJSON)

myJSON_d.['DataSet'].update({'values': values, 'timeStamps': timeStamps})

myJSON = json.dumps(myJSON_d)

You can parse the JSON with json.loads , do the manipulation, and then convert back to JSON via json.dumps .

Note that I had to edit your JSON to make it valid. ("Gateway" was missing the enclosing double quotes.)

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"]}}

Looks like you are trying to construct the json too. In that case you should just do this:

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))

Returns:

{
  "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"
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM