jsobj["a"]["b"]["e"].append({"f":var3, "g":var4, "h":var5})
jsobj["a"]["b"]["e"].append({"f":var6, "g":var7, "h":var8})
Answer from DrTyrsa on Stack Overflowjsobj["a"]["b"]["e"].append({"f":var3, "g":var4, "h":var5})
jsobj["a"]["b"]["e"].append({"f":var6, "g":var7, "h":var8})
Just add the dictionary as a dictionary object not a string :
jsobj["a"]["b"]["e"].append(dict(f=var3))
Full source :
var1 = 11
var2 = 32
jsonobj = {"a":{"b":{"c": var1,
"d": var2,
"e": [],
},
},
}
var3 = 444
jsonobj["a"]["b"]["e"].append(dict(f=var3))
jsonobj will contain :
{'a': {'b': {'c': 11, 'd': 32, 'e': [{'f': 444}]}}}
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"]}}
Add values to JSON object in Python - Stack Overflow
Append JSON array with another item using Python - Stack Overflow
python - How to add an element to a list? - Stack Overflow
How to add json array to a json document in python? - Stack Overflow
Videos
First, accidents is a dictionary, and you can't write to a dictionary; you just set values in it.
So, what you want is:
for accident in accidents:
accident['Turn'] = 'right'
The thing you want to write out is the new JSON—after you've finished modifying the data, you can dump it back to a file.
Ideally you do this by writing to a new file, then moving it over the original:
with open('sanfrancisco_crashes_cp.json') as json_file:
json_data = json.load(json_file)
accidents = json_data['accidents']
for accident in accidents:
accident['Turn'] = 'right'
with tempfile.NamedTemporaryFile(dir='.', delete=False) as temp_file:
json.dump(temp_file, json_data)
os.replace(temp_file.name, 'sanfrancisco_crashes_cp.json')
But you can do it in-place if you really want to:
# notice r+, not rw, and notice that we have to keep the file open
# by moving everything into the with statement
with open('sanfrancisco_crashes_cp.json', 'r+') as json_file:
json_data = json.load(json_file)
accidents = json_data['accidents']
for accident in accidents:
accident['Turn'] = 'right'
# And we also have to move back to the start of the file to overwrite
json_file.seek(0, 0)
json.dump(json_file, json_data)
json_file.truncate()
If you're wondering why you got the specific error you did:
In Python—unlike many other languages—assignments aren't expressions, they're statements, which have to go on a line all by themselves.
But keyword arguments inside a function call have a very similar syntax. For example, see that tempfile.NamedTemporaryFile(dir='.', delete=False) in my example code above.
So, Python is trying to interpret your accident['Turn'] = 'right' as if it were a keyword argument, with the keyword accident['Turn']. But keywords can only be actual words (well, identifiers), not arbitrary expressions. So its attempt to interpret your code fails, and you get an error saying keyword can't be an expression.
I solved with that :
with open('sanfrancisco_crashes_cp.json') as json_file:
json_data = json.load(json_file)
accidents = json_data['accidents']
for accident in accidents:
accident['Turn'] = 'right'
with open('sanfrancisco_crashes_cp.json', "w") as f:
json.dump(json_data, f)
model.fruits = {"id": 1, "name": "apple"}* defines a dictionary, you cannot append to a dictionary, you can add keys to it
You can append elements into a JSON array though, e.g. if model.fruits was an array (or a list, as it is called in Python), e.g.
model.fruits = [{"id": 1, "name": "apple"},]
which defines an array with 1 element in it, then you can append to it
model.fruits.append({"id": 2, "name": "banana"})
Some references:
https://docs.djangoproject.com/en/1.8/ref/contrib/postgres/fields/#hstorefield https://docs.djangoproject.com/en/1.8/ref/contrib/postgres/fields/#arrayfield
* To be honest it doesn't make sense to name something in the plural like fruits to hold a single object, should be a container, like a list
In Django, you should make a new model called Fruit.
class Fruit(models.Model):
name = models.Charfield(max_length=50)
in your main model you should have a ManyToManyField.
fruits = models.ManyToManyField(Fruit, blank=True, related_name='model')
This way you would be able to add some more fields in future do filtering and whole other things.
To add a fruit to model object
obj.fruits.add(1, 2) # where 1 and 2 are id's of fruits to add
I would do this:
data["list"].append({'b':'2'})
so simply you are adding an object to the list that is present in "data"
Elements are added to list using append():
>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}
If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead:
>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}
After doing that, you can assemble JSON again from dictionary you modified:
>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'
As mentioned in the comments, once loaded the json is a python dictionary. You should now iterate on the value of the 'data' key, extract the information and store them in a list.
Something like this should do the job:
json_obj = json.load(json1)
ips = []
for piece in json_obj['data']:
this_ip = [piece['custom3'], piece['modemId']]
ips.append(this_ip)
One line form:
ips = [[piece['custom3'], piece['modemId']] for piece in json_obj['data']]
If you just want this
ips = [["custom3","modemId"],["custom3","modemId"]]
Then all you need is a simple list comprehension
ips = [d.keys() for d in json1_obj['data']]
If you want to actually get the values (in order), not the keys
ips = [ [ d['custom3'], d['modemId'] ] for d in json1_obj['data']]