3

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,

2

3 Answers 3

5

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)
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.