如何将数据附加到json文件? [英] How to append data to a json file?

查看:185
本文介绍了如何将数据附加到json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个将条目添加到json文件的函数.最终,我想要一个看起来像

I'm trying to create a function that would add entries to a json file. Eventually, I want a file that looks like

[{"name" = "name1", "url" = "url1"}, {"name" = "name2", "url" = "url2"}]

等这就是我所拥有的:

def add(args):
    with open(DATA_FILENAME, mode='r', encoding='utf-8') as feedsjson:
        feeds = json.load(feedsjson)
    with open(DATA_FILENAME, mode='w', encoding='utf-8') as feedsjson:
        entry = {}
        entry['name'] = args.name
        entry['url'] = args.url
        json.dump(entry, feedsjson)

这确实会创建一个条目,例如{"name"="some name", "url"="some url"}.但是,如果我再次使用此add函数,并使用不同的名称和URL,则第一个函数将被覆盖.我该怎么做才能将第二个(第三个...)条目附加到第一个?

This does create an entry such as {"name"="some name", "url"="some url"}. But, if I use this add function again, with different name and url, the first one gets overwritten. What do I need to do to get a second (third...) entry appended to the first one?

编辑:对这个问题的第一个答案和评论指出了一个明显的事实,即我没有在写块中使用feeds.不过,我看不出该怎么做.例如,以下内容显然不会:

EDIT: The first answers and comments to this question have pointed out the obvious fact that I am not using feeds in the write block. I don't see how to do that, though. For example, the following apparently will not do:

with open(DATA_FILENAME, mode='a+', encoding='utf-8') as feedsjson:
    feeds = json.load(feedsjson)
    entry = {}
    entry['name'] = args.name
    entry['url'] = args.url
    json.dump(entry, feeds)

推荐答案

json可能不是磁盘格式的最佳选择.附加数据带来的麻烦就是为什么会出现这种情况的一个很好的例子.具体地说,json对象的语法意味着必须读取并解析整个对象才能理解其中的任何部分.

json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it.

幸运的是,还有许多其他选择. CSV特别简单. python的标准库很好地支持了这一点.最大的缺点是,它仅适用于文本.如果需要,程序员需要采取其他措施才能将值转换为数字或其他格式.

Fortunately, there are lots of other options. A particularly simple one is CSV; which is supported well by python's standard library. The biggest downside is that it only works well for text; it requires additional action on the part of the programmer to convert the values to numbers or other formats, if needed.

另一个不受此限制的选项是使用sqlite数据库,该数据库在python中也具有内置支持.这可能与您已经拥有的代码有更大的不同,但是它更自然地支持您显然试图构建的稍微修改"模型.

Another option which does not have this limitation is to use a sqlite database, which also has built-in support in python. This would probably be a bigger departure from the code you already have, but it more naturally supports the 'modify a little bit' model you are apparently trying to build.

这篇关于如何将数据附加到json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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