Bootstrap FreeKB - Python (Scripting) - Parse JSON using the json filter
Python (Scripting) - Parse JSON using the json filter

Updated:   |  Python (Scripting) articles

There are several built in modules that are part of the Python Standard Library included with your Python installation, such as os (Operating System) and re (Regular Expression) and sys (System).

There are a number of different ways to parse JSON.

  • json.load - parse a JSON file
  • json.loads - parse JSON (key:value pairs)
  • json.dumps - get the json output of a dictionary
  • json.tool - parse JSON on the command line
  • .json() filter - parse JSON results (this article)

The .json() filter is typically used after a GET request has been made to an API that returns JSON, like this.

#!/usr/bin/python
import requests

response = requests.get("http://www.example.com/api")
print(response.json())

 

Which could return something like this.

{
    "foo": "Hello",
    "bar": "World"
}

 

And here is how you could print the value from a certain key in the JSON.

#!/usr/bin/python3
import requests

response = requests.get("http://www.example.com/api")
print(f"foo = {response.json()['foo']}")
print(f"bar = {response.json()['bar']}")

 

Which could return something like this.

foo = Hello
bar = World



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter bb5f9d in the box below so that we can be sure you are a human.