Bootstrap FreeKB - Python (Scripting) - Parse dictionary using json.dumps and json.loads
Python (Scripting) - Parse dictionary using json.dumps and 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).

In Python, there are similar functions that are used to parse JSON.

 

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
dictionary = {}

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

print(f"dictionary  = {dictionary}")
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 and no exceptions are raised.

raw json    = {}
parsed json = {}

 

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

#!/usr/bin/python3
import json
dictionary = { "foo": "hello" }

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

print(f"dictionary  = {dictionary}")
print(f"parsed json = {parsed_json}")

 

Running this script should now raise the following exception.

Traceback (most recent call last):
  File "testing.py", line 4, in <module>
    parsed_json = json.loads(str(dictionary))
  File "/usr/lib64/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

 

json.dumps must be used convert the dictionary into JSON and then json.loads is used to parse the JSON into a format that can be properly interpreted by Python.

#!/usr/bin/python3
import json
dictionary = { "foo": "hello" }

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

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

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

 

Running this script should now return the following.

dictionary  = {'foo': 'hello'}
raw json    = {"foo": "hello"}
parsed json = {u'foo': u'hello'}

 




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