将元素添加到JSON文件? [英] Add element to a JSON file?

查看:61
本文介绍了将元素添加到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

这篇关于将元素添加到JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆