-3

I've been trying to get JSON response out of the following code, but it's throwing an error

from requests import get 
import json
url = "https://api.wheretheiss.at/v1/satellites/25544"
response = get(url)
for item in response:
    print(item, response[item])

I wanna print the JSON in the following format:

https://i.stack.imgur.com/ZWMbr.png

rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
  • 1
    Please read the docs: https://docs.python-requests.org/en/master/user/quickstart/#json-response-content – DeepSpace Sep 22 '21 at 14:24
  • What is the error? Also don't post screenshots of text. – Pranav Hosangadi Sep 22 '21 at 14:24
  • print out `response.text`. Use a json viewer (here's my [preferred one](https://codebeautify.org/jsonviewer)) to visualize it. once you understand the data structure, you can then access it. – rv.kvetch Sep 22 '21 at 14:26
  • Please show us the full error. Simply saying "it's throwing an error" isn't useful in diagnosing the problem. – Kemp Sep 22 '21 at 14:27
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Sep 30 '21 at 09:48

2 Answers2

0

your code works well to get the correct respone from the url. The problem is that you should parse the raw respone as the json format. Please refer to the following code:

from requests import get 
import json
url = "https://api.wheretheiss.at/v1/satellites/25544"
response = get(url)

# dump response into json
result = response.content.decode('utf-8')
result = json.loads(result)
print(result) # print raw json

# print as key-value pairs
for item in result:
    print("{0} : {1}".format(item, result[item]))

The output is like following: Example output

user6379829
  • 61
  • 1
  • 1
-1

I think you're misunderstanding what the response contains.

Your initial code is good.

from requests import get 
import json
url = "https://api.wheretheiss.at/v1/satellites/25544"
response = get(url)

You now have a response. see here for more info.

In this response you have status_code, content, encoding, and the response content as text. it also contains other information about the request. eg we don't want to continue if the request failed

You can simply parse the json by calling json.loads on the decoded response via response.text

parsed_json = json.loads(response.text)
or
parsed_json  = response.json()

for item in json_:
    print(item, json_[item])

I hope it helps. it is also duplicate to HTTP requests and JSON parsing in Python

Doommius
  • 3
  • 1