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}]}}}
append an array to a json python - Stack Overflow
python - How to add an element to a list? - Stack Overflow
Add values to JSON object in Python - Stack Overflow
Append JSON array with another item using Python - Stack Overflow
Videos
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"]}}
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"}]}'
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
... the JSON array at the end of your answer is incorrect, but to generate an array, just give a list to json.dumps in Python. Something like json_data_list = []; ... ; json_data_list.append(json_data); ... print(json.dumps(json_data_list)); ...
Your JSON file is incorrect. Normally you must have a structure as:
{
"key1": [
{
"id": "blabla",
"name": "Toto"
},
{
"id": "blibli",
"name": "Tata"
}
],
"key2": {
"id": "value"
},
"key3": "value"
}
So I think you have to change your JSON array for example as following:
{
[
{
"id": 0,
"organizer": "Some Name",
"eventStart": "09:30 AM",
"eventEnd": "10:00 AM",
"subject": "rental procedure",
"attendees": "Some Name<br />Person 2<br />Person 3"
},
{
"id": 1,
"organizer": "Some Name",
"eventStart": "09:30 AM",
"eventEnd": "10:00 AM",
"subject": "rental procedure",
"attendees": "Some Name<br />Person 2<br />Person 3"
},
{
"id": 2,
"organizer": "Some Name",
"eventStart": "09:30 AM",
"eventEnd": "10:00 AM",
"subject": "rental procedure",
"attendees": "Some Name<br />Person 2<br />Person 3"
}
]
}
You can decide also to have not a list of dictionary as I proposed above but to use the ID value as key for each dictionary; in that case you have:
{
"id0":{
"organizer": "Some Name",
"eventStart": "09:30 AM",
"eventEnd": "10:00 AM",
"subject": "rental procedure",
"attendees": "Some Name<br />Person 2<br />Person 3"
},
"id1":{
"organizer": "Some Name",
"eventStart": "09:30 AM",
"eventEnd": "10:00 AM",
"subject": "rental procedure",
"attendees": "Some Name<br />Person 2<br />Person 3"
},
"id2":{
"organizer": "Some Name",
"eventStart": "09:30 AM",
"eventEnd": "10:00 AM",
"subject": "rental procedure",
"attendees": "Some Name<br />Person 2<br />Person 3"
}
}