将元素添加到python中的json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22296496/
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 00:43:16  来源:igfitidea点击:

Add element to a json in python

pythonjson

提问by Biribu

I am trying to add an element to a json file in python but I am not able to do it.

我正在尝试向 python 中的 json 文件添加一个元素,但我无法做到。

This is what I tried untill now (with some variation which I deleted):

这是我到目前为止所尝试的(我删除了一些变化):

import json

data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 } ]
print 'DATA:', repr(data)

var = 2.4
data.append({'f':var})
print 'JSON', json.dumps(data)

But, what I get is:

但是,我得到的是:

DATA: [{'a': 'A', 'c': 3.0, 'b': (2, 4)}]
JSON [{"a": "A", "c": 3.0, "b": [2, 4]}, {"f": 2.4}]

Which is fine because I also need this to add a new row instead an element but I want to get something like this:

这很好,因为我还需要它来添加一个新行而不是一个元素,但我想得到这样的东西:

[{'a': 'A', 'c': 3.0, 'b': (2, 4), "f":2.4}]

How should I add the new element?

我应该如何添加新元素?

采纳答案by Jayanth Koushik

You can do this.

你可以这样做。

data[0]['f'] = var

回答by Vincent Claes

alternatively you can do

或者你可以做

iter(data).next()['f'] = var

回答by Johan Sulaiman

One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:

我看到的一个可能的问题是您在数组/列表对象中非常规地设置了 JSON。我会建议使用 JSON 以其最被接受的形式,即:

test_json = { "a": 1, "b": 2}

Once you do this, adding a json element only involves the following line:

执行此操作后,添加 json 元素仅涉及以下行:

test_json["c"] = 3

This will result in:

这将导致:

{'a': 1, 'b': 2, 'c': 3}

Afterwards, you can add that json back into an array or a list of that is desired.

之后,您可以将该 json 添加回所需的数组或列表中。