David
David

Reputation: 69

Is there a way to print out certain elements of the JSON file in python?

I am using a (dutch) weather API and the result is showing a lot of information. However, I only want to print the temperature and location. Is there a way to filter out these keys?

from pip._vendor import requests
    

import json

response = requests.get(" http://weerlive.nl/api/json-data-10min.php?key=demo&locatie=52.0910879,5.1124231")


def jprint(obj):
    weer = json.dumps(obj, indent=2)
    print(weer)

jprint(response.json())

result:

{
  "liveweer": [
    {
      "place": "Utrecht",
      "temp": "7.7",
      "gtemp": "5.2",
      "summa": "Dry after rain",
      "lv": "89",
       etc.

How do I only print out the place and temp? Thanks in advance

Upvotes: 1

Views: 1137

Answers (4)

sarartur
sarartur

Reputation: 1228

If you are only interested in working with place and temp I would advise making a new dictionary.

import requests

r = requests.get(" http://weerlive.nl/api/json-data-10min.php?key=demo&locatie=52.0910879,5.1124231")

if r.status_code == 200:
    data = {
        "place" : r.json()['liveweer'][0]["place"], 
        "temp":  r.json()['liveweer'][0]["temp"],
    }
    print(data)
    

Upvotes: 0

buran
buran

Reputation: 14253

import requests
response = requests.get(" http://weerlive.nl/api/json-data-10min.php?key=demo&locatie=52.0910879,5.1124231")
data = response.json()
for station in data["liveweer"]:
    print(f"Temp in {station['plaats']} is {station['temp']}")

output

Temp in Utrecht is 8.0

Note that you can use convenient Response.json() method

Upvotes: 2

Mengard
Mengard

Reputation: 222

If you expect the API to returns you a list of place, you can do:

>>> {'liveweer': [{'plaats': item['plaats'], 'temp': item['temp']}] for item in response.json()['liveweer']}
{'liveweer': [{'plaats': 'Utrecht', 'temp': '8.0'}]}

Upvotes: 1

IoaTzimas
IoaTzimas

Reputation: 10624

Try this:

x=response.json()

print(x['liveweer'][0]['place'])
print(x['liveweer'][0]['temp'])

Upvotes: 1

Related Questions