英文:
Python is outputting dictionary as a single string instead of an organised list of values, how do I fix this?
问题
它不是以有序的格式返回的,是否有办法让其返回为一个列表,无论是我需要下载另一个软件来正确读取这些数据,还是在代码中有一些格式化的方法?我希望数据输出如下...
"id": 2059,
"name": "球队",
"logo": "logo.png",
"winner": false
Python 代码如下:
import requests
url = "https://api-football-v1.p.rapidapi.com/v3/fixtures"
querystring = {"date": "2023-03-09"}
headers = {
"X-RapidAPI-Key": "[在此处输入密钥,已隐藏]",
"X-RapidAPI-Host": "[在此处输入主机,已隐藏]"
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)
尝试输出到 Excel,但它将所有数据放入一个单元格,而不是多行和多列。
英文:
I'm using an API to return football data, however when I run the code the code returns the data as a long string which I cannot do anything with:
Its not in an organised format, is there any way to make this return as a list whether it be I need to download another software to correctly read this or is there some way of formatting in the code? I'd like the data to output as follows...
"id":2059,
"name":"Team",
"logo": "logo.png",
"winner": false
Python Code Used:
import requests
url = "https://api-football-v1.p.rapidapi.com/v3/fixtures"
querystring = {"date":"2023-03-09"}
headers = {
"X-RapidAPI-Key": "[key goes here,hidden]",
"X-RapidAPI-Host": "[host goes here,hidden]"
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)
Tried outputting to excel but it puts all the data into 1 cell as opposed to many rows and columns
答案1
得分: 0
正如一位评论者所提到的,您有一个JSON对象,而不仅仅是一个字符串。您可以像这样将其视为字典:
import requests
url = "https://api-football-v1.p.rapidapi.com/v3/fixtures"
querystring = {"date": "2023-03-09"}
headers = {
"X-RapidAPI-Key": "[key goes here,hidden]",
"X-RapidAPI-Host": "[host goes here,hidden]"
}
response = requests.request("GET", url, headers=headers, params=querystring)
data = response.json() # <---- 这是改变的部分。
然后,您可以根据需要操作该字典以处理数据或将其写入文件。
英文:
As a commenter mentioned, you have a JSON object, not just a string. You can access this as a dictionary like so:
import requests
url = "https://api-football-v1.p.rapidapi.com/v3/fixtures"
querystring = {"date":"2023-03-09"}
headers = {
"X-RapidAPI-Key": "[key goes here,hidden]",
"X-RapidAPI-Host": "[host goes here,hidden]"
}
response = requests.request("GET", url, headers=headers, params=querystring)
data = response.json() # <---- this is the change.
You can then manipulate the dictionary as needed to process the data or write it to a file.
答案2
得分: 0
PirateNinjas的解决方案在这种情况下是正确的。 requests
库已经提供了JSON解析功能。然而,还有一种更一般的方法可以将JSON字符串转换为Python对象:
import json
obj = json.loads(json_string)
英文:
PirateNinjas' solution is the right solution in this case. requests
library already provides the JSON parsing capability. However, there is a more general way of transforming JSON strings into Python objects:
import json
obj = json.loads(json_string)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论