Python - 将JSON对象附加到现有JSON对象

时间:2017-02-06 22:09:01

标签: python json file

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

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

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

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

当我尝试跑步时:

const routes: Routes = [
  {
    path: '',
    component: StartPage
  },
  {
    path: 'unmanaged/:controllerId/:activeGroupId',
    component: UnmanagedPage
  },
  {
    path: 'edge',
    component: EdgeComponent,
    canActivate: [AuthGuard],
    children: [
      { path: '', component: DevicesPage, pathMatch: 'full' },
      { path: 'devices', component: DevicesPage },
      { path: 'device/:id', component: DeviceDetailsPage },
      { path: 'device-edit/:id', component: DeviceEditPage},
      { path: 'device-add', component: DeviceAddPage },

      { path: 'groups', component: GroupsPage },

      { path: 'cyber-score', component: CyberScorePage },
      { path: 'profile', component: ProfilePage },
      { path: 'profile-edit', component: ProfileEditPage }
    ]
  },
  {
    path: 'guest',
    component: GuestComponent,
    children: [
      { path: 'device', component: GuestDeviceDetailsPage }
    ]
  },
  {
    path: '**',
    component: PageNotFoundPage
  }
];

我的数据格式不正确。你能否告诉我如何正确附加到文本文件?

2 个答案:

答案 0 :(得分:2)

这可能不是处理您请求的最Pythonic方式,但我希望它可以帮助解决您可能遇到的一些问题。我将加载和转储包装到try-except手镯中,以使代码更加健壮。 我自己最大的惊喜是,在打开文件作为输出文件时不要使用'a'而是'w'。但是,如果您认为已经在“data.append(data1)”行中添加,那么这是完全合理的,因此在转储到文件时不需要追加两次。

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

try:
    with open('append.txt', 'r') as fin:
        data = json.load(fin)
except FileNotFoundError as exc:
    pass

try:
    if data:
        data.append(data1)
        with open('append.txt', 'w') as fout:
            json.dump(data, fout)
except UnboundLocalError as exc:
    with open('append.txt', 'w') as fout:
        json.dump(data, fout)

答案 1 :(得分:1)

首先从文件中读取数据。

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

然后将数据附加到旧数据

data = old_data + data

然后重写整个文件。

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