代码之家  ›  专栏  ›  技术社区  ›  RickeDz

将json请求保存到文件[重复]

  •  -1
  • RickeDz  · 技术社区  · 3 年前

    感谢您的关注!

    我正在python上执行for循环和“请求url”,并获得“json”响应,希望将所有循环添加到一个文件中,以便稍后在excel或其他json阅读器上读取。。。

    for x in range(1, 6):
        url = f"https://api.xxx.com.br/ecommerce-web/api/parceiro/meuCadastro/{x}/true"
        response = requests.get(url, headers=headers)
        print(response.json())
    

    所以在这个循环之后,我得到了5个这样的回复

    {'A': 1, 'Name': 'Name01'}
    {'A': 2, 'Name': 'Name02'}
    {'A': 3, 'Name': 'Name03'}
    {'A': 4, 'Name': 'Name04'}
    {'A': 5, 'Name': 'Name05'}
    

    我想做一个包含所有答案的json文件,谢谢大家!我刚开始刷网络。

    解决这个问题将所有答案添加到json文件中

    1 回复  |  直到 3 年前
        1
  •  0
  •   Jedddo    3 年前

    您可以使用内置的json库来编写json文件。

    import json
    
    data = []  # save all responses here
    
    for x in range(1, 6):
        url = f"https://api.xxx.com.br/ecommerce-web/api/parceiro/meuCadastro/{x}/true"
        response = requests.get(url, headers=headers)
        data.append(response.json())  # append every json response
    
    
    with open("myjson.json", "w") as file:  # "w" will create myjson.json if it doesn't exist, otherwise rewrite the whole file
        json.dump(data, file, indent=4)  # dump all the data into the json file with 4 space indentation