问题
I have a Json object and Im trying to add a new element every time I enter a new number. The Json looks like this:
[
{
"range": [1,2,3,4,5]
}
]
This is my code:
import json
number = raw_input("enter a number: ")
json_file = 'json.json'
json_data = open(json_file)
data = json.load(json_data)
data.append({"range": number})
print data
If my new number is 10 for example, I want my new json document to have: [1, 2, 3, 4, 5, 10]. The output I'm getting with my code is:
[{u'range': [1, 2, 3, 4, 5]}, {'range': '25'}]
I'm using python 2.6
回答1:
You need something like this
data[0]['range'].append(10)
Or use int(your_number) instead of 10
回答2:
Your json object consists of:
- single element list
- first element of list is mapping with single key (range)
- this key value is a list
To append to this list you have to:
- take first element from list -
data[0] - take a correct value from mapping -
data[0]['range'] - append to retrieved list -
data[0]['range'].append(new_value)
回答3:
First of all for opening a file you can use with statement which will close the file the the end of the block, the you can load your json file and after that you can will have a list contains a dictionary which you can access to dictionary with index 0 and access to the list value with data[0]['range'] and finally you can append your number list :
import json
number = raw_input("enter a number: ")
json_file = 'json.json'
with open(json_file) as json_data:
data = json.load(json_data)
data[0]['range'].append(int(number))
print data
来源:https://stackoverflow.com/questions/32611532/append-element-into-a-json-object-python