简体   繁体   中英

Append element into a json object python

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

You need something like this

data[0]['range'].append(10)

Or use int(your_number) instead of 10

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)

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

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