将元素添加到JSON文件?

将元素添加到JSON文件?

问题描述:

我正在尝试将元素添加到python中的json文件中,但是我无法做到这一点.

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

这是我直到现在尝试过的内容(删除了一些变化):

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)

但是,我得到的是:

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?

您可以执行此操作.

data[0]['f'] = var