代码之家  ›  专栏  ›  技术社区  ›  W. Stephens

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

  •  0
  • W. Stephens  · 技术社区  · 9 年前

    {"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

    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 回复  |  直到 9 年前
        1
  •  0
  •   Hou Lu    9 年前

    首先定义一个基础 dict 要保存您的ID:

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

    out 使用源JSON:

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

    js_dict就是您上面提到的JSON。