从JSON中删除ID,然后将其添加到每组数据中。

时间:2017-07-27 00:48:33

标签: python json

我一直在运行一个Python脚本,它删除每组数据的ID,以允许它上传到BigQuery。现在,我想将其插入到每组数据中,而不是删除此信息,以便稍后可以引用它。

这就是我收到我上传到Bigquery的JSON以及代码的方式。

{"AppName": "DataWorks", "foundedPeripheralCount": 1, "version": "1.6.1(8056)", "deviceType": "iPhone 6", "createdAt": "2017-04-05T07:05:30.408Z", "updatedAt": "2017-04-05T07:08:49.569Z", "connectedPeripheralCount": 1, "iOSVersion": "10.2.1"}

-

firebase = firebase.FirebaseApplication('https://dataworks-356fa.firebaseio.com/')
result = firebase.get('/PeripheralCount', None)
id_keys = map(str, result.keys()) #filter out ID names


with open("firetobq_peripheral2.json", "w") as outfile:
  for id in id_keys:
    json.dump(result[id], outfile, indent=None)
    outfile.write("\n")

这是在没有任何编辑的情况下创建JSON的方式。

{"1972FDEE-E2C0-4E8C-BD00-630315D4AEDE": {"AppName": "DataWorks", "foundedPeripheralCount": 1, "version": "1.6.1(8056)", "deviceType": "iPhone 6", "connectedPeripheralCount": 1, "updatedAt": "2017-04-05T07:08:49.569Z", "Peripherals": {"1CA726ED-32B1-43B4-9071-B58BBACE20A8": "Arduino"}, "createdAt": "2017-04-05T07:05:30.408Z", "iOSVersion": "10.2.1"}

1972FDEE-E2C0-4E8C-BD00-630315D4AEDE是ID。

firebase = firebase.FirebaseApplication('https://dataworks-356fa.firebaseio.com/')
result = firebase.get('/PeripheralCount', None)
id_keys = map(str, result.keys()) #filter out ID names


with open("firetobq_peripheralx.json", "w") as outfile:
  # for id in id_keys:
  json.dump(result, outfile, indent=None)
  outfile.write("\n")

我希望它看起来像这样。

{"ID": "1972FDEE-E2C0-4E8C-BD00-630315D4AEDE", "AppName": "DataWorks", "foundedPeripheralCount": 1, "version": "1.6.1(8056)", "deviceType": "iPhone 6", "connectedPeripheralCount": 1, "updatedAt": "2017-04-05T07:08:49.569Z", "Peripherals": {"1CA726ED-32B1-43B4-9071-B58BBACE20A8": "Arduino"}, "createdAt": "2017-04-05T07:05:30.408Z", "iOSVersion": "10.2.1"}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

首先定义基地dict以保存您的ID:

out = {
    "ID": "1972FDEE-E2C0-4E8C-BD00-630315D4AEDE",
}

然后,使用原点JSON更新out

out.update(js_dict.get(out.get('ID')))

js_dict是你上面提到的JSON。