
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 (this article)
- json.tool - parse JSON on the command line
- .json() filter - parse JSON results
json.dumps is typically used when attempting to visualize input JSON or trying to debug some issue with json.load or json.loads.
Here is how you can parse a dictionary (key:value pairs) using json.dumps.
AVOID TROUBLE
Do not name the variable that stores json.dumps "json". In other words, do not use json = json.dumps(dictionary) as this overrides the json object, causing all sorts of issues.
#!/usr/bin/python3
import json
dictionary = { "name": "John Doe" }
try:
json_dump = json.dumps(dictionary)
except Exception as exception:
print(f"Got the following exception: {exception}")
print(json_dump)
Running this Python script should return the following.
{"name": "John Doe"}
With single quotes around the keys and values in the dictionary.
#!/usr/bin/python3
import json
dictionary = { 'name': 'John Doe' }
try:
json_dump = json.dumps(dictionary)
except Exception as exception:
print(f"Got the following exception: {exception}")
print(json_dump)
json.dumps changes the single quotes to double quotes.
{"name": "John Doe"}
With single quotes around the dictionary and double quotes around the keys and values in the dictionary.
#!/usr/bin/python3
import json
dictionary = '{ "name": "John Doe" }'
try:
json_dump = json.dumps(dictionary)
except Exception as exception:
print(f"Got the following exception: {exception}")
print(json_dump)
The values and keys in the dictionary are escaped.
"{ \"name\": \"John Doe\" }"
With double quotes around and inside the dictionary.
#!/usr/bin/python3
import json
dictionary = "{ "name": "John Doe" }"
try:
json_dump = json.dumps(dictionary)
except Exception as exception:
print(f"Got the following exception: {exception}")
print(json_dump)
Return the following.
File "dump.py", line 3
dictionary = "{ "name": "John Doe" }"
^
SyntaxError: invalid syntax
Did you find this article helpful?
If so, consider buying me a coffee over at