繁体   English   中英

如何将多个API请求写入有效的JSON文件?

[英]How do I write multiple API requests to a valid JSON file?

我正在尝试在python脚本中请求多个api调用。 现在我的代码已设置好,我正在使用请求进行连接并循环访问API网址。 JSON响应已写入文件,因此我可以在外部处理数据。 我能够建立连接并将响应写到文件中而不会出现问题。 但是,当我尝试在jsonlint中验证完成的文件时会出现问题,这告诉我我有多个顶级字段,这些字段看起来是响应头。 因此,问题是如何遍历我的API以编写单个有效的JSON文件?

到目前为止,我已经尝试将JSON响应更改为python字典,但是现在我对下一步尝试感到有些茫然。

这是我的请求/文件写作片段:

for x, y in sites[data[z]].items():
    url = "".join(y['host'] + endpoint + 'customer_id=' + y['customer_id'] +
                  '&requestor_id=' + y['requestor_id'] + '&api_key=' + y['api_key'])
    urls = url + "&begin_date=" + begin + "&end_date=" + end

    r = requests.get(urls)  # make connections to vendors
    print("Connection Status: ", r.status_code)  # print http response code

    try:
        r.json()  # get data from vendors
    except json.decoder.JSONDecodeError:
        print(urls, "This is not a JSON format..")  # catch vendor JSON errors

    print("I'm saving your usage statistics to a text file.")
    with open(reportName + '-' + begin + '-' + end + '.json', 'a') as datafile:
        json.dump(r.json(), datafile)  # write api resp to .JSON file

    print("I'\'m done writing your usages to file:" + reportName + '-' + begin
          + '-' + end + ".json.")

这是api响应

{  
   "Report_Header":{  },
   "Report_Items":[  ]
}{  
   "Report_Header":{  },
   "Report_Items":[  ]
}

这里:

with open(reportName + '-' + begin + '-' + end + '.json', 'a') as datafile:
    json.dump(r.json(), datafile)

您要将json片段附加到同一文件,实际上并不会产生有效的json-即:

# cat youfile.json
{'foo': 'bar'}{'foo': 'baaz'}{'foo': 42}

无效。

如果要将所有收集的数据保存在同一个文件中,则必须首先将它们收集到一个列表中(或字典,但必须为每个json代码段提供密钥),然后再将结果转储到在写入模式(以确保为空白)。

您可以构建这种形式的JSON文件,而不是将所有响应收集在列表中然后编写它们,

{"responses":[
   {  
   "Report_Header":{  },
   "Report_Items":[  ]
   },
   {  
   "Report_Header":{  },
   "Report_Items":[  ]
   }
 ]
}

实际上是有效的json对象。 您可以通过对代码进行以下修改来实现:

with open(fileName, 'a') as datafile:
    datafile.write('{"responses":[')

for x, y in sites[data[z]].items():
    url = "".join(y['host'] + endpoint + 'customer_id=' + y['customer_id'] +
                  '&requestor_id=' + y['requestor_id'] + '&api_key=' + y['api_key'])
    urls = url + "&begin_date=" + begin + "&end_date=" + end

    r = requests.get(urls)  # make connections to vendors
    print("Connection Status: ", r.status_code)  # print http response code

    try:
        r.json()  # get data from vendors
    except json.decoder.JSONDecodeError:
        print(urls, "This is not a JSON format..")  # catch vendor JSON errors

    print("I'm saving your usage statistics to a text file.")
    with open(fileName, 'a') as datafile:
        json.dump(r.json(), datafile)  # write api resp to .JSON file
        datafile.write(",") # add comma for JSON array element

with open(fileName, 'a') as datafile:
    datafile.seek(0, os.SEEK_END) # Move to last 
    datafile.seek(datafile.tell() - 1, os.SEEK_SET) # back One character
    datafile.truncate() # Delete the last comma ","
    datafile.write(']}')

print("I'\'m done writing your usages to file:" + fileName)

现在,您可以根据需要解析JSON文件以供外部使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM