Python (Scripting) - Parse JSON using the json filter

by
Jeremy Canfield |
Updated: November 25 2024
| 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 - convert a dictionary into json
- 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