Append element into a json object python

余生长醉 提交于 2021-02-08 07:19:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!