【问题标题】:How to format JSON data when writing to a file写入文件时如何格式化 JSON 数据
【发布时间】:2016-11-12 00:32:27
【问题描述】:

我正在尝试获取此 api 请求并在将其转储到 JSON 文件时对其进行格式化。每当我这样做时,它都是一个字符串并且很难阅读。我试过添加缩进,但它没有做任何事情。如果需要,我可以提供 API 密钥。

import json, requests

url = "http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID={APIKEY}"
response = requests.get(url)
response.raise_for_status()

with open('weather.json', 'w') as outfile:
     json.dump(response.text, outfile, indent=4)

【问题讨论】:

  • indent 参数应该可以工作。您是否从以前的尝试中查看过陈旧的文件,新的尝试失败并且不再接触文件?

标签: python json api formatting request


【解决方案1】:

我认为您的代码存在一些问题。

首先,将不相关的导入写在单独的行上而不是用逗号分隔被认为是更好的形式。我们一般只在做from module import thing1, thing2之类的事情时才使用逗号。

我假设您在 URL 中留下了 {APIKEY} 作为占位符,但以防万一:您需要在此处插入 您的 API 密钥。您可以按原样通过.format 调用来执行此操作。

您致电response.raise_for_status()。这应该包含在 try/except 块中,因为如果请求失败,这会引发异常。您的代码会出错,届时您将成为 SOL。

但最重要的是:response.text 是一个字符串json.dump 仅适用于字典。你需要一本字典,所以使用response.json() 来获取它。 (或者,如果您想先操作 JSON,可以通过 json_string = json.loads(response.text) 从字符串中获取它。)


这就是它可能会出现的结果:

import json
import requests

# Replace this with your API key.
api_key = '0123456789abcdef0123456789abcdef'

url = ("http://api.openweathermap.org/data/2.5/forecast/city?"
       "id=524901&APPID={APIKEY}".format(APIKEY=api_key))
response = requests.get(url)

try:
    response.raise_for_status()
except requests.exceptions.HTTPError:
    pass
    # Handle bad request, e.g. a 401 if you have a bad API key.

with open('weather.json', 'w') as outfile:
     json.dump(response.json(), outfile, indent=4)

【讨论】:

  • 完美运行,感谢您的帮助。我想我需要回去学习基础知识!
  • @Mark 乐于助人!如果我的回答解决了您的问题,请花一点时间单击它的复选框以“接受”它作为您问题的正确答案。将不胜感激。 :)
【解决方案2】:

response.json() 是你的朋友。我已经测试了下面的代码(当然使用不同的 API 端点返回 json 数据),它对我来说很好,如果这对你有用,请告诉我。

with open('weather.json', 'w') as outfile:
     json.dump(response.json(), outfile, indent=4) # response.json() is here now :)

【讨论】:

    猜你喜欢
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    相关资源
    最近更新 更多