Search code examples
pythonjsonapikey

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


Solution

  • 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'}]}