Skip to main content
 首页 » 编程设计

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

2025年05月04日26rubylouvre

我正在尝试获取此 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)