Updated July 1, 2023
Definition of Python Object to JSON
Python Object to JSON is a method of serialization of a Python class object into JSON (JavaScript Object Notation) string object. This method helps us to convert a Python class object into JSON, which is a more compact format than a Python object. In this method, we use the “JSON” package, which is a part of the Python programming language itself (built-in), and use the JSON.dumps() method to convert a Python class object into a flat JSON string object. The JSON is a lightweight data format due to which we save space by converting a Python class object into a JSON string object (python class objects consume more space than the JSON object).
In this article, we will cover how to convert a Python class object to a JSON string object with hands-on example codes with output as well.
Install the package
Before you can start converting a Python object into a json object, the first thing that you have to do is install a package that allows you to do so. We have a “json” package in Python to deal with this conversion and which can be installed with the code syntax mentioned below:
#installing json package
This package has “json.dumps()” and “json. dump()” functions which allow us to convert the Python object into a JSON object. However, these two procedures have a basic difference, as mentioned below:
- dump() function, on the other hand, does an additional job than converting the object; it allows you to write that formatted change into a file.
You can convert different types of Python objects into JSON strings such as int, string, list, tuple, dict, float, bol, etc. The functions discussed above will help you in the conversion of a Python object to an equivalent JSON object based on the table below:
Python to JSON Conversion Table
Python Object to be Converted | Equivalent JSON Object |
str | string |
int | number |
float | number |
True | true |
False | false |
list | Array |
tuple | Array |
dict | Object |
None | null |
Examples
Let us see a basic example that covers the conversion of all these datatypes above into a JSON string in Python.
Example #1
Code:
import json
#Converting different python objects into an equivalent JSON string
name = "Dell Vostro" #Str
print(json.dumps(name))
ram_in_gb = 4 #Int
print(json.dumps(ram_in_gb))
price = 37500.98 #Float
print(json.dumps(price))
touch = False #Bool
print(json.dumps(touch))
wifi = True #Bool
print(json.dumps(wifi))
Graphic = None #None
print(json.dumps(Graphic))
list1 = ["Dell Vostro", 4, 37500.98] #List
print(json.dumps(list1))
touple1 = ("Dell Vostro", 4, 37500.98) #Touple
print(json.dumps(touple1))
dict1 = {"name" : "Dell Vostro", "price" : 37500.98, "wifi" : True} #Dict
print(json.dumps(dict1))
Here, we have enclosed the object of each data type into json.dumps() function to convert it into a JSON string. See below the output of this code once run.
Here, in this example, all details associated with my laptop are considered as different data types usually deal with. The equivalent JSON objects can be seen in the output screenshot above.
Interestingly, we can create a Python object with all these data types together and then convert it into a json string as well. Note that the final output will be a dictionary of a JSON string. See the code associated with it as shown below:
Example #2
Code:
import json
#Converting a python object into a JSON string
together = json.dumps(
{
"name" : "Dell Vostro",
"ram_in_gb" : 4,
"price" : 37500.98,
"touch" : False,
"wifi" : True,
"Graphic" : None,
"list1" : ["Dell Vostro", 4],
"touple1" : ("Dell Vostro", 37500.98)
})
print(together)
Here, we have created a dictionary with multiple data types (string, int, bool, etc.), and all these details are provided as input to json.dumps() function. It is stored in a variable named together so that we can print it later. Finally, the json.dumps() function is used to convert this object (a dictionary) to JSON (output will be a dictionary with JSON string data types). See the output as shown below:
If you see the output, keywords are retained as keywords in the JSON string dictionary, and values for those keywords are converted into equivalent JSON data types.
We can customize the JSON output with a few customization Arguments in the code above. See it below:
#Customizing the code with additional arguments
together = json.dumps(
{
"name" : "Dell Vostro",
"ram_in_gb" : 4,
"price" : 37500.98,
"touch" : False,
"wifi" : True,
"Graphic" : None,
"list1" : ["Dell Vostro", 4],
"touple1" : ("Dell Vostro", 37500.98)
}, sort_keys=True, indent = 4)
print(together)
Here, in this code, the two additional arguments (apart from the object argument) we have used under the json.dumps() function. The first argument, “sort_keys = True,” allows the system to generate output in a manner that keys are sorted in alphabetical order. The second argument, “indent = 4,” specifies how many indentations should be used while generating the output.
Example #3
Let us use the json.dump() function to create a JSON file.
Code:
import json
#creating a file with name user.json in working directory
with open('user.json','w') as file:
json.dump({
"name" : "Lalit",
"age" : 28,
"active" : True,
"married" : False,
"pets" : None,
"amount": 450.98,
"siblings": ["Mona", "Shyam", "Pooja"],
"languages" : ("English", "German", "Spanish")
},
file, sort_keys= True, indent=4)
Here in this code, we have used the json.dump() function in combination with open() to create a JSON file named user.json in the working directory. Let us see the file in the working directory:
If we try to open this file in any text editor, we will have the same dictionary of JSON string as in the above example. Please find below is the screenshot for your reference:
This article ends here. However, before closing it off, let’s note a few conclusion points.
Conclusion
- The Python to Object to JSON converts objects into a JSON string formatted object.
- We have the “json” package that allows us to convert objects into JSON.
- The json. dumps() function converts/serializes an object into an equivalent JSON string object and returns the output in console.
- The json.dump() function, instead of returning the output in the console, allows you to create a JSON file in the working directory.
Recommended Articles
This is a guide to Python Object to JSON. Here we discuss the Definition and install the package and Python to JSON Conversion Table with examples. You may also have a look at the following articles to learn more –