如何将元素添加到 json 列表 - python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30350450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:18:37  来源:igfitidea点击:

how to add element to json list - python

pythonjson

提问by doniyor

From this

由此

data = json.loads(urlopen('someurl').read())

I will get:

我会得到:

{'list': [{'a':'1'}]}

I want to add {'b':'2'}into the list.

我想添加{'b':'2'}list.

Any idea how to do it?

知道怎么做吗?

采纳答案by pinturic

I would do this:

我会这样做:

data["list"].append({'b':'2'})

so simply you are adding an object to the list that is present in "data"

因此,您只需将一个对象添加到“数据”中存在的列表中

回答by myaut

Elements are added to list using append():

使用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:

如果要将元素添加到列表中的特定位置(即开头),请insert()改用:

>>> 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:

>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'

回答by Waldeyr Mendes da Silva

import json

myDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}
test = json.dumps(myDict)
print(test)

{"dict": [{"a": "none", "b": "none", "c": "none"}]}

{"dict": [{"a": "none", "b": "none", "c": "none"}]}

myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))
test = json.dumps(myDict)
print(test)

{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}

{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", " c": "aaaa"}]}