Bootstrap FreeKB - Python (Scripting) - Parse JSON using json.loads
Python (Scripting) - Parse JSON using json.loads

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) (this article)
  • json.dumps - get the json output of a dictionary
  • json.tool - parse JSON on the command line
  • .json() filter - parse JSON results

Here is how you can parse a dictionary (key:value pairs) using json.loads. In this example dictionary is empty with no keys and no values.

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
raw_json = '{}'

try:
  parsed_json = json.loads(raw_json)
except Exception as exception:
  print(f"Got the following exception: {exception}")

print(f"raw json    = {raw_json}")
print(f"parsed json = {parsed_json}")

 

Running this Python script should return the following. In this scenario, there are no differences between the raw JSON and the parsed JSON.

raw json    = {}
parsed json = {}

 

However, let's do the same with JSON that contains keys and values.

#!/usr/bin/python3
import json
raw_json = '{"foo": "Hello", "bar": "World"}'

try:
  parsed_json = json.loads(raw_json)
except Exception as exception:
  print(f"Got the following exception: {exception}")

print(f"raw json    = {raw_json}")
print(f"parsed json = {parsed_json}")

 

Now the following should be returned, where we can see that the parsed JSON has been parsed into a format that can be properly interpreted by Python.

raw json    = {"foo": "Hello", "bar": "World"}
parsed json = {u'foo': u'Hello', u'bar': u'World'}

 

In this example JSON contains a single key (name) with no value.

#!/usr/bin/python3
import json
raw_json = '{ "name": "" }'

try:
  parsed_json = json.loads(raw_json)
except Exception as exception:
  print(f"Got the following exception: {exception}")

print(f"raw json    = {raw_json}")
print(f"parsed json = {parsed_json}")

 

Which should return the following.

raw json    = { "name": "" }
parsed json = {u'name': u''}

 

An if statement can be used to determine if a key exists.

#!/usr/bin/python3
import json
raw_json = '{ "name": "" }'

try:
  parsed_json = json.loads(raw_json)
except Exception as exception:
  print(f"Got the following exception: {exception}")

if 'name' in parsed_json:
  print("The name key exists")

 

Running this Python script should return the following.

The name key exists

 

In this example dictionary contains a single key (name) with a value (John Doe).

#!/usr/bin/python3
import json
raw_json = '{ "name": "John Doe" }'

try:
  parsed_json = json.loads(raw_json)
except Exception as exception:
  print(f"Got the following exception: {exception}")

if 'name' in parsed_json:
  print(parsed_json['name'])

 

Which should return the following.

John Doe

 

In this example dictionary contains a nested key (name below employees) with a value (John Doe).

#!/usr/bin/python
import json
raw_json = '{ "employees": { "name": "John Doe" } }'

try:
  parsed_json = json.loads(raw_json)
except Exception as exception:
  print(f"Got the following exception: {exception}")

if 'employees' in parsed_json:
  print("The employees key exists")
  if 'name' in parsed_json['employees']:
    print("The name key exists")
    print(parsed_json['employees']['name'])

 

Which should return the following.

The employees key exists
The name key exists
John Doe

 




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 f32c4d in the box below so that we can be sure you are a human.