python - 写入文件时如何格式化JSON数据

标签 python json api formatting request

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

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)

最佳答案

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

首先,将不相关的导入写在单独的行上而不是用逗号分隔被认为是更好的形式。我们通常只在执行诸如 from module import thing1, thing2 之类的操作时使用逗号。

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

您调用 response.raise_for_status()。这应该包含在 try/except block 中,因为如果请求失败,这将引发异常。您的代码会吐出来,到那时您将成为 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)

关于python - 写入文件时如何格式化JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38283596/

相关文章:

python - 在Python中动态应用setter装饰器

python - AWS Lambda 记录到一个 JSON 行

java - 如何在Java中解析格式为 "\/Date(1339638938087-0500)\/"的日期字符串?

javascript - eval(responseText) + Javascript + JSON + Rails 之后无法读取数组

c# - System.Text.Json:将 JSON 转换为十进制值 "NA"

java - 使用 Java StarTeam API,我如何找到 StarTeam 项的哪些修订版具有特定标签?

javascript - 我们如何在 postman 测试中断言 bool 数据类型

python - 如何设置 Gamma 校正的最佳值

python - 如何检查列表中的值是否为字符串?

java - java中的xml文件