
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write JSON in Python
In this article, we will learn different types of methods to write JSON in python.
Conversion Rules
When converting a Python object to JSON data, the dump() method follows the conversion rules listed below ?
Python |
JSON |
---|---|
dict |
object |
list, tuple |
array |
str |
string |
int, float |
number |
True |
true |
False |
false |
None |
null |
Writing Dictionary into a JSON File
The function of json.dump() is to arrange a Python object into a JSON formatted stream into the specified file.
Syntax
dump(obj, fp, *, skipkeys=False, check_circular=True, allow_nan=True, indent=None, separators=None, default=None, sort_keys=False, **kw)
Parameters
obj ? obj is known as object that arranges as a JSON formatted stream.
fp ?the fp also know as file object will store JSON data.
skipkeys ? The default value is False. It ignores the Keys of dict that are not of a basic type. Orelse, it will throw a TypeError.
check_circular ? It's default value is True. It's main task is to perform circular reference check for container types. This sometimes get the output result in an OverflowError.
allow_nan ? It's e default value is True. If false, serializing out-of-range float values will result in a ValueError.It uses JavaScript equivalents like -NaN, Infinity, -Infinity by default.
indent ? It is used for good printing with a specified order.
separators ? These are the ones used in the JSON.
default ? this function is called when an object fails to serialized. It either returns object's JSON-encoded version or throw a TypeError. If no type is given, a TypeError is defaulty thrown.
sort_keys ? It's default value is False. If true, the dictionaries' output will be ordered/sorted by key.
Example
The following program converts the given dictionary to a JSON file using the json.dump() function ?
# importing json module import json # creating a dictionary inputDict = { "website": "Tutorialspoint", "authorName": "xyz", "Age": 25, "Address": "hyderabad", "pincode":"503004" } # opening a JSON file in write mode with open('outputfile.json', 'w') as json_file: # writing the dictionary data into the corresponding JSON file json.dump(inputDict, json_file)
Output
On executing, the above program will generate the following output ?
{"website": "Tutorialspoint", "authorName": "xyz", "Age": 25, "Address": "hyderabad", "pincode": "503004"}
A file named outputfile.json is created containing the above dictionary data.
Using the Indent Parameter
Use the indent parameter of the method dump() for attractive printing.
Example
The following program converts the given dictionary to a pretty JSON file with indentation using the json.dump() function and indent argument ?
# importing JSON module import json # creating a dictionary inputDict = { "website": "Tutorialspoint", "authorName": "xyz", "Age": 25, "Address": "hyderabad", "pincode":"503004" } # opening a JSON file in write mode with open('outputfile.json', 'w') as json_file: # writing the dictionary data into the corresponding JSON file # by adding indent parameter to make it attractive with proper indentation json.dump(inputDict, json_file, indent=5)
Output
On executing, the above program will generate the following output ?
{ "website": "Tutorialspoint", "authorName": "xyz", "Age": 25, "Address": "hyderabad", "pincode": "503004" }
A file named outputfile.json is created containing the above dictionary data with a proper indentation for making it more pretty.
Sorting the Keys in JSON
We can sort the keys of a dictionary alphabetically using the sort_keys = True parameter.
The following program converts the given dictionary to a sorted JSON file with indentation using the json.dump() function and sort_keys argument?
# importing JSON module import json # creating a dictionary inputDict = { "website": "Tutorialspoint", "authorName": "xyz", "Age": 25, "Address": "hyderabad", "pincode":"503004" } # opening a JSON file in write mode with open('outputfile.json', 'w') as json_file: # writing the dictionary data into the corresponding JSON file # indent parameter- to make it attractive with proper indentation # sort_keys- sorts the dictionary keys alphabetically json.dump(inputDict, json_file, indent=5, sort_keys=True)
Output
{ "Address": "hyderabad", "Age": 25, "authorName": "xyz", "pincode": "503004", "website": "Tutorialspoint" }
The keys are now sorted alphabetically, as seen above.
Separators are an additional argument that can be used. In this, you can use any separator you like (", ", ": ", ",", ":").
Converting Python List to JSON
Example
The following program converts the python list to JSON string using dumps() function ?
# importing JSON module import json # input list inputList = [2, 4, 6, 7] # converting input list into JSON string using dumps() function jsonString = json.dumps(inputList) # printing the resultant JSON string print(jsonString) # printing the type of resultant JSON string print(type(jsonString))
Output
[2, 4, 6, 7] <class 'str'>
Converting Directories Python List to JSON
Example
The following program converts the Directories python list to JSON string. using dumps() function ?
# importing json module import json # input list of dictionaries list_dict = [{'x':10, 'y':20, 'z':30}, {'p':40, 'q':50}] # converting list of dictionaries into json string jsonData = json.dumps(list_dict) # printing the JSON data print(jsonData)
Output
[{"x": 10, "y": 20, "z": 30}, {"p": 40, "q": 50}]
Converting Python List of Lists to JSON
Example
The following program converts the Python List of Lists to JSON string using dumps() function ?
# importing JSON module import json # input list of lists list_of_list = [[{'x':10, 'y':20, 'z':30}], [{'p':40, 'q':50}]] # converting a list of list into JSON string jsonString = json.dumps(list_of_list) # printing the resultant JSON string print(jsonString)
Output
[[{"x": 10, "y": 20, "z": 30}], [{"p": 40, "q": 50}]]
Conclusion
This article contains a variety of techniques for converting various data formats to JSON files, JSON strings, etc. json.dumps(), which is used to convert any form of iterable to JSON, has also been covered in depth.