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

使用Python删除json文件中的新行馈送。

  •  3
  • W. Stephens  · 技术社区  · 7 年前

    我正在从firebase下载数据,并将其导出为json。在此之后,我试图将其上传到bigquery,但我需要删除bigquery的新行提要才能接受它。

    {   "ConnectionTime": 730669.644775033, 
        "objectId": "eHFvTUNqTR", 
        "CustomName": "Relay Controller", 
        "FirmwareRevision": "FW V1.96", 
        "DeviceID": "F1E4746E-DCEC-495B-AC75-1DFD66527561", 
        "PeripheralType": 9, 
        "updatedAt": "2016-12-13T15:50:41.626Z", 
        "Model": "DF Bluno", 
        "HardwareRevision": "HW V1.7", 
        "Serial": "0123456789", 
        "createdAt": "2016-12-13T15:50:41.626Z", 
        "Manufacturer": "DFRobot"}
    {
        "ConnectionTime": 702937.7616419792, 
        "objectId": "uYuT3zgyez", 
        "CustomName": "Relay Controller", 
        "FirmwareRevision": "FW V1.96", 
        "DeviceID": "F1E4746E-DCEC-495B-AC75-1DFD66527561", 
        "PeripheralType": 9, 
        "updatedAt": "2016-12-13T08:08:29.829Z", 
        "Model": "DF Bluno", 
        "HardwareRevision": "HW V1.7", 
        "Serial": "0123456789", 
        "createdAt": "2016-12-13T08:08:29.829Z", 
        "Manufacturer": "DFRobot"}
    

    {"ConnectionTime": 730669.644775033,"objectId": "eHFvTUNqTR","CustomName": "Relay Controller","FirmwareRevision": "FW V1.96","DeviceID": "F1E4746E-DCEC-495B-AC75-1DFD66527561","PeripheralType": 9,"updatedAt": "2016-12-13T15:50:41.626Z","Model": "DF Bluno","HardwareRevision": "HW V1.7","Serial": "0123456789","createdAt": "2016-12-13T15:50:41.626Z","Manufacturer": "DFRobot"}
    {"ConnectionTime": 702937.7616419792, "objectId": "uYuT3zgyez", "CustomName": "Relay Controller", "FirmwareRevision": "FW V1.96", "DeviceID": "F1E4746E-DCEC-495B-AC75-1DFD66527561", "PeripheralType": 9, "updatedAt": "2016-12-13T08:08:29.829Z", "Model": "DF Bluno", "HardwareRevision": "HW V1.7", "Serial": "0123456789", "createdAt": "2016-12-13T08:08:29.829Z", "Manufacturer": "DFRobot"}
    

    我正在使用python加载json,读取它,然后编写一个新的json,但无法找到正确的代码。非常感谢。

    下面是我的python代码的大纲

    import json
    with open('nospacetest.json', 'r') as f:
      data_json=json.load(f)
    
    #b= the file after code for no line breaks is added
    
    with open('testnoline.json', 'w') as outfile:
      json.dump=(b, outfile)
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   Shai    7 年前

    你只需要确保 indent=None 当你 dump

    with open('testnoline.json', 'w') as outfile:   
        json.dump(data_json, outfile, indent=None)
    

    引用文件:

    indent 是一个非负整数,那么JSON数组元素和对象成员将以该缩进级别打印出来。缩进级别为0或负值时,只会插入换行符。 None (默认值)选择最紧凑的表示。

        2
  •  3
  •   user94559    7 年前

    with open('testnoline.json', 'w') as outfile:
        for obj in data_json:
            outfile.write(json.dumps(obj) + "\n")