Python-将JSON对象附加到现有JSON对象 [英] Python - Appending JSON object to exisiting JSON object

查看:126
本文介绍了Python-将JSON对象附加到现有JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JSON对象附加到文本文件中的现有JSON对象.我的第一组数据看起来像这样.

I am trying to append JSON objects to existing JSON object in text file. My first set of data look likes this.

data = [
        {
          "username": "Mike",
          "code": "12345",
          "city": "NYC"
        }
      ]

然后我需要向现有文件中添加另一组JSON对象,如下所示:

Then I need to append another set of JSON objects to existing file to look like this:

data = [
        {
          "username": "Mike",
          "code": "12345",
          "city": "NYC"
        },
        {
          "username": "Kelly",
          "code": "56789",
          "city": "NYC"
        }
      ]

当我尝试运行时:

with open('data2.txt', 'a') as outfile:
    json.dump(data, outfile)

我的数据不是正确的JSON格式.您能否建议如何正确添加到文本文件?

my data is not in correct JSON format. Can you please advise how to append to text file correctly?

推荐答案

首先从文件中读取数据.

First read the data from the file.

with open('data2.txt') as data_file:    
    old_data = json.load(data_file)

然后将您的数据附加到旧数据

Then append your data to the old data

data = old_data + data

然后重写整个文件.

with open('data2.txt', 'w') as outfile:
    json.dump(data, outfile)

这篇关于Python-将JSON对象附加到现有JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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