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

Mar*_*ark 1 python api formatting json request

我正在尝试获取此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)
Run Code Online (Sandbox Code Playgroud)

Pie*_*agh 5

我认为你的代码有几个问题.

首先,在不同的行上编写不相关的导入而不是用逗号分隔,这被认为是更好的形式.我们通常只在使用逗号时使用逗号from module import thing1, thing2.

我假设你离开{APIKEY}的URL作为占位符,但以防万一:你需要插入有API密钥.您可以.format按原样拨打电话.

你打电话response.raise_for_status().这应该包含在try/except块中,因为如果请求失败,则会引发异常.你的代码只是barf,那时你就是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=apiKey))
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)
Run Code Online (Sandbox Code Playgroud)