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 (this article)
- 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
Let's say you have a JSON file named example.json that contains the following.
{
"foo": "Hello World"
}
Here is how you can load the JSON file into a variable.
AVOID TROUBLE
Do not name the variable that stores json.loads "json". In other words, do not use json = json.loads(dictionary) as this overrides the json object, causing all sorts of issues.
#!/usr/bin/python3
import json
file = open("/path/to/example.json")
try:
parsed_json = json.load(file)
except Exception as exception:
print(f"Got the following exception: {exception}")
file.close()
print(parsed_json)
You may want or need to include the encoding as well.
#!/usr/bin/python3
import json
file = open("/path/to/example.json")
try:
parsed_json = json.load(file, encoding="utf8")
except Exception as exception:
print(f"Got the following exception: {exception}")
file.close()
print(parsed_json)
Which should return the following.
{u'foo': u'Hello World'}
Here is how you can access the JSON keys and values.
#!/usr/bin/python3
import json
file = open("/path/to/example.json")
try:
parsed_json = json.load(file)
except Exception as exception:
print(f"Got the following exception: {exception}")
file.close()
for key in parsed_json:
print(f"key = {key}")
print(f"value = {parsed_json[key]}")
Which should return the following.
key = foo
value = Hello World
Here is how you can return the value of the "foo" key in Python.
#!/usr/bin/python3
import json
file = open("/path/to/example.json")
try:
parsed_json = json.load(file)
except Exception as exception:
print(f"Got the following exception: {exception}")
file.close()
if "foo" in parsed_json:
print parsed_json['foo']
else:
print "/path/to/example.json does not contain a key named \"foo\""
Nested
Let's say you have nested JSON, like this.
{
"main":
{
"department":
{
"username": "john.doe"
}
}
}
Here is how you can return the value of the "username" key.
#!/usr/bin/python3
import json
file = open("/path/to/example.json")
try:
parsed_json = json.load(file)
except Exception as exception:
print(f"Got the following exception: {exception}")
file.close()
if "main" in parsed_json:
print("the main key exists")
if "department" in parsed_json['main']:
print("the main.department key exists")
if "username" in parsed_json['main']['department']:
print("the main.department.username key exists")
print(parsed_json['main']['department']['username'])
Loop
Let's say you have JSON like this.
{
"main": [
{
"foo": "Hello"
},
{
"foo": "World"
}
]
}
Here is how you could loop through the JSON, printing the value of the "foo" key.
#!/usr/bin/python3
import json
file = open("/path/to/example.json")
try:
parsed_json = json.load(file)
except Exception as exception:
print(f"Got the following exception: {exception}")
file.close()
for key in parsed_json["main"]:
print(key["foo"])
Did you find this article helpful?
If so, consider buying me a coffee over at