How to convert a dictionary to JSON in Python?
Dictionaries are one of the most widely used data structures in Python, while JSON is a highly recognized format for data. To make data represented by a dictionary usable in the JSON format, we would first need to convert it to JSON
Before the code demonstration, let's first concisely cover both of these individually.
JSON format
JSON, also known as JavaScript Object Notation, is an efficient and lightweight interchange format to efficiently depict data that is both easy to read or write for us and for machines to parse and generate.
JSON rules to remember
This format consists of key-value pairs which are then enclosed in curly braces.
The key and the value are separated using a colon.
The keys are always a string.
The value could be of various types, for instance, booleans, arrays, strings, objects, null, etc.
Keys can be repeated since they are ordered, but it is not recommended.
The keys and values must be enclosed in double quotes.
{"blackHole": {"name": "Cygnus X-1","type": "Stellar","mass": 15,"isSupermassive": false,"isRotating": true,"spin": 0.98,"discoveredBy": null,"aliases": ["HDE 226868"],"details": {"discoveryDate": "1964","distance": 6100.0,"galacticCoordinates": {"l": 71.335,"b": -3.063}}}}
Dictionaries in Python
A dictionary is a built-in data structure that Python provides us with. It allows us to hold key-value pairs as a collection and is similar to maps or hash tables. We can say that it's a mutable, unordered, and indexed collection of elements. It's also similar to JSON due to these key-value pairs.
Dictionary rules in Python
The format includes the dictionary's name followed by an
sign which is finally followed by the dictionary content in curly braces. The keys must be unique and immutable.
Single quotes can be used for keys and values.
Dictionaries can grow or shrink since elements can be added, removed, or modified.
Values can be of any type, including mutable objects like lists or even dictionaries.
The keys could be any hashable object and aren't limited to strings.
blackHole = {'name': 'Cygnus X-1','type': 'Stellar','mass': 15,'isSupermassive': False,'isRotating': True,'spin': 0.98,'discoveredBy': None,'aliases': ['HDE 226868'],42: 'Meaning of Life',('x', 'y'): 'Coordinates',True: 'Boolean Key'}
We're now equipped with the necessary knowledge and can convert a dictionary to JSON.
Converting a dictionary to JSON
json.dumps method
The json module in Python offers functionalities related to encoding and decoding data in JSON. Since our goal is to convert a dictionary to this format, we can make use of the dumps function put forth by this module.
Syntax
jsonData = json.dumps(dictName)
Parameters
The only necessary argument to be passed to this function is the dictionary input itself. Apart from that, there are a few optional parameters we can add for customizations.
indent: Specifies the number of spaces for indentation in the JSON string.sort_keys: Controls whether keys in the JSON string are sorted alphabetically.separators: Customizes the separators used in the JSON string.ensure_ascii: Determines whether non-ASCII characters are escaped in the JSON string.
Note: Escaping means representing non-ASCII characters using a Unicode escape sequence.
The result
The variable to which the json.dump method assigns the result now contains a JSON formatted string.
Let's see this in action now!
Code sample
import json
star = {
'name': 'Sirius',
"spectral_type": 'A1V',
'temperature': '9640K',
'distance_ly': 8.6,
'discovery_year': 1844,
'aliases': ['Dog Star'],
'details': {
'constellation': 'Canis Major',
'right_ascension': '06h 45m 08.9173s',
'declination': '-16 42 58.017',
'main_sequence': True
}
}
JSONData = json.dumps(
star,
indent = 4,
sort_keys = True,
separators = (",", ": "),
ensure_ascii = False
)
print(JSONData)
Code explanation
Line 1: We import the
jsonmodule in Python.Lines 3–18: We define a dictionary named
starwith the keysname,spectral_type,temperature,distance_ly,aliases, anddetails.Line 20: A variable JSONData is created so that it can be assigned the JSON object after conversion. We call the
json.dumpsmethod to achieve this conversion.Line 21: We pass the
stardictionary to this method.Line 22: We pass
indent = 4tojson.dumpsto specify that the resulting JSON string should be indented with 4 spaces for better readability.Line 23: We pass
sort_keys = Truetojson.dumpsto ensure that the keys in the resulting JSON string are sorted in alphabetical order.Line 24: We pass
separators = (",", ": ")tojson.dumpsto specify that a comma and space should be used as the element separator while a colon and space should be used as the key-value separator.Line 25: Lastly, we pass
ensure_ascii = Falsetojson.dumpsto ensure that non-ASCII characters in the input data are preserved without escaping.Line 26: Our dictionary is now finally converted and stored in
JSONData! We can finally print it to see the result usingprint(JSONData).
Output
Congratulations, our code is now ready to run! The following image depicts the output of the star dictionary we converted to JSON.
You can also experiment with the executable code above to convert your own dictionary when you click on "Run".
Test yourself now!
Consider the following dictionary:
data = {"b": 2, "a": 1, "c": 3}.
If we use the json.dumps method with sort_keys = True to convert this to a JSON string, what will be the output?
Free Resources