Python is outputting dictionary as a single string instead of an organised list of values, how do I fix this?

Question:

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:

Returned Data Here

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

Asked By: Excel_Tom

||

Answers:

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.

Answered By: PirateNinjas

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)
Answered By: Green绿色
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.