写入文件时如何格式化JSON数据(How to format JSON data when writing to a file)

编程入门 行业动态 更新时间:2024-10-28 10:22:47
写入文件时如何格式化JSON数据(How to format JSON data when writing to a file)

我试图得到这个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)

I'm trying to get this api request and have it formatted when I dump it into the JSON file. Whenever I do, its all one string and very hard to read. I've tried adding the indent but it didn't do anything. I can provide the API key if needed.

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时候使用逗号。

我假设您将URL中的{APIKEY}作为占位符离开,但以防万一:您需要在其中插入您的 API密钥。 您可以按照.format使用.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)

There are a couple problems with your code, I think.

First of all, it's considered better form to write unrelated imports on separate lines instead of separated by a comma. We generally only use commas when doing things like from module import thing1, thing2.

I'm assuming you left {APIKEY} in the URL as a placeholder, but just in case: you will need to insert your API key there. You can do this with a .format call as-is.

You call response.raise_for_status(). This ought to be wrapped in a try/except block since if the request fails, this raises an exception. Your code will just barf and you'll be SOL at that point.

But here's the most important thing: the response.text is a string. json.dump only works with dictionaries. You'll need a dictionary, so use response.json() to get it. (Alternatively, if you wanted to manipulate the JSON first, you could get it from the string by doing json_string = json.loads(response.text).)


Here's what it should probably come out to:

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)

更多推荐

本文发布于:2023-08-01 13:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1360127.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   数据   JSON   format   writing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!