EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Python Object to JSON

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » Python Tutorial » Python Object to JSON

Python Object to JSON

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 light-weight 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.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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:

  • dumps() function converts(serializes) a python object into a string that is JSON formatted.
  • 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 string 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))

Popular Course in this category
Python Training Program (36 Courses, 13+ Projects)36 Online Courses | 13 Hands-on Projects | 189+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.8 (8,421 ratings)
Course Price

View Course

Related Courses
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)Angular JS Training Program (9 Courses, 7 Projects)

Here, we have enclosed the object of each data type into json.dumps() function in order to convert it into a JSON string. See below is the output of this code once run.

Python Object to JSON 1

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 python dictionary with multiple data types (string, int, bool, etc.) and all these details are provided as input to json.dumps() function. It is stored into a variable named together so that we can print it later. Finally, the json.dumps() function is used to convert this python object (a dictionary) to JSON (output will be a dictionary with JSON string data types). See the output as shown below:

Python Object to JSON 2

If you see the output, keywords are retained as keywords in JSON string dictionary and values for those keywords are converted into equivalent JSON data types. A point to note here is, siblings and languages are both converted into an array in resultant JSON (previously were a list and a tuple respectively).

We can customize the JSON output with few customization Arguments in the code above. See it as 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 in the python.

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. The json.dump() function itself is used when we want to create a file of JSON objects that are converted from the original python objects. Let us see the file in the working directory:

Python Object to JSON 3

After running the code above, a JSON file gets created 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:

file user

This article ends here. However, before closing it off, let’s make a note of few conclusion points.

Conclusion

  • The python to Object to JSON is a method of converting python objects into a JSON string formatted object.
  • We have the “json” package that allows us to convert python objects into JSON.
  • The json.dumps() function converts/serialize a python object into equivalent JSON string object and return the output in console.
  • The json.dump() function instead of returning the output in console, allows you to create a JSON file on 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 –

  1. Python Object to String
  2. Python pip
  3. Python Stream
  4. Python json.dumps

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Python Tutorial
  • Programs
    • Patterns in Python
    • Star Patterns in Python
    • Swapping in Python
    • Factorial in Python
    • Fibonacci Series in Python
    • Reverse Number in Python
    • Palindrome in Python
    • Random Number Generator in Python
    • Prime Numbers in Python
    • Armstrong Number in Python
    • Strong Number in Python
    • Leap Year Program in Python
    • Square Root in Python
    • Python Reverse String
    • Python Object to String
    • Python Object to JSON
    • Python Classmethod vs Staticmethod
  • Basics Part I
    • Introduction To Python
    • What Is Python
    • Careers in Python
    • Advantages of Python
    • Uses of Python
    • Python Features
    • Python Fast And python psyco
    • Python ImportError
    • Benefits and Limitations of Using Python
    • What can I do with?Python
    • Is Python a scripting language
    • Is Python Object Oriented
    • Is Python Open Source
    • Python Socket Programming
    • Useful Tips on Python Programming
    • Python You Should Be Using It
    • Python Web Development
    • Python Programming Beginners Tutorails
    • Practical Python Programming for Non-Engineers
    • Python Programming for the Absolute Beginner
    • Versions of?Python
  • Basic Part II
    • Comments in Python
    • Finally in Python
    • Python Multiline Comment
    • Python Data Types
    • Python Variables
    • Python Variable Types
    • Python Global Variable
    • Python Variable Scope
    • Python Private Variables
    • Python Default Arguments
    • Python Command-line Arguments
    • Indentation in Python
    • Object in Python
    • Python Keywords
    • Python Literals
    • Pointers in Python
    • Iterators in Python
    • Python User Input
    • Python Enumerate
    • Python Commands
    • Type Casting in Python
    • Python Identifiers
    • Python Constants
    • What is NumPy in Python?
    • Cheat Sheet Python
  • Frameworks
    • Python Frameworks
    • Python Compilers
    • Python Editors
    • Best Compiler for Python
    • Python IDE for Windows
    • Python IDE on Linux
  • Installation
    • How To Install Python
    • Install Python on Linux
    • Install Python on Windows
    • Install Anaconda Python
  • Operator
    • Python Operators
    • Arithmetic Operators in Python
    • Python Comparison Operators
    • Logical Operators in Python
    • Assignment Operators in Python
    • Unary Operators in Python
    • String Operators in Python
    • Boolean Operators in Python
    • Identity Operators in Python
    • Python Bitwise Operator
    • Python Remainder Operator
    • Python Modulus Operator
  • Control Statement
    • Conditional Statements in Python
    • Control Statements in Python
    • If Condition in Python
    • If Statement in Python
    • If Else Statement in Python
    • else if Statement in Python
    • Nested IF Statement in Python
    • Break Statement in Python
    • Python Switch Statement
  • Loops
    • Loops in Python
    • For Loop in Python
    • While Loop in Python
    • Do While Loop in Python
    • Python Nested Loops
    • Python Infinite Loop
    • Python Event Loop
  • Sorting
    • Sorting in Python
    • Sorting Algorithms in Python
    • Bubble Sort in Python
    • Merge Sort in Python
    • Heap Sort in Python
    • Quick Sort in Python
    • Python Sorted Function
  • Function
    • Python Built-in Functions
    • Math Functions in Python
    • Python String Functions
    • Trigonometric Functions in Python
    • Python Input Function
    • Python Input String
    • Python String Operations
    • Python Stream
    • Python Multiline String
    • Python Regex
    • Python Regex Tester
    • Python regex replace
    • Python File Methods
    • Python Import CSV
    • Python Read CSV File
    • Python write CSV file
    • Python Delete File
    • Python File readline
    • Python if main
    • Python Main Method
    • List Method in Python
    • Python List Length
    • Recursive Function in Python
    • Copy List in Python
    • Python Range Function
    • Python Substring
    • Python list remove()
    • Python List Index
    • Python Set Function
    • Python len Function
    • Python eval()
    • Python Counter
    • ord Function in Python
    • strip Function in Python
    • Split Function in Python
    • Python Round Function
    • Python Map Function
    • Python String Join
    • Python format() Function
    • Python Contextlib
    • Python Compare Strings
    • Python Return Value
    • Python List count
    • Filter in Python
    • Python Slice String
    • Python Absolute Value
    • Python Trim String
    • Python Type Function
    • Lowercase in Python
    • Python xrange
    • Python yield
    • Python Find String
    • Max Function in Python
    • Python Power Function
    • pop() in Python
    • Python argparse
    • Python Pickle
    • Python Zip Function
    • Python Split String
    • super() in Python
    • Python Extend
    • Python String Replace
    • Python PEP8
    • Python Filter Function
    • Python if then else
    • Lambda in Python
    • Python BeautifulSoup
    • Python Sleep
    • Python Function Generator
    • Python @classmethod decorator
    • Python Endswith
    • Python BufferedReader
    • Python Async
    • Python Parser
    • Python SystemExit
    • Python pip
    • Python kwargs
  • Array
    • Arrays in Python
    • 2D Arrays In Python
    • 3d Arrays in Python
    • Multidimensional Array in Python
    • Python Array Functions
    • String Array in Python
    • Python Sort Array
    • Python Array Length
  • Inheritance
    • Inheritance in Python
    • Single Inheritance in Python
    • Multiple Inheritance in Python
    • Interface in Python
  • Exception
    • Python Exception Handling
    • Custom Exception in Python
    • Indentation Error in Python
    • Python IOError
    • Python EOFError
    • Python NotImplementedError
    • Python TypeError
    • Python ValueError
    • Python AssertionError
    • Python Unicode Error
    • Python NameError
    • Python StopIteration
    • Python OverflowError
    • Python KeyboardInterrupt
  • Advanced
    • Scope in Python
    • Python Collections
    • Constructor in Python
    • Destructor in Python
    • Python Overloading
    • Overriding in Python
    • Function Overloading in Python
    • Method Overloading in Python
    • Operator Overloading in Python
    • Method Overriding in Python
    • Encapsulation in Python
    • Static Method in Python
    • Assert in Python
    • Python References
    • Python Virtualenv
    • Python mkdir
    • Logistic Regression in Python
    • Dictionary in Python
    • Regular Expression in Python
    • Python Import Module
    • Python OS Module
    • Python Sys Module
    • Python Generators
    • Abstract Class in Python
    • Python File Operations
    • Sequences in Python
    • Stack in Python
    • Queue in Python
    • Tuples in Python
    • Python Magic Method
    • Python Sets
    • Python Set Methods
    • Priority Queues in Python
    • Reverse Engineering with Python
    • String Formatting in Python
    • Python isinstance
    • String Length Python
    • Python Concurrency
    • Python List
    • Python Initialize List
    • Python Unique List
    • Python Sort List
    • Python Reverse List
    • Python Empty List
    • List Comprehensions Python
    • List Operations in Python
    • Python Database Connection
    • Python SQLite
    • Python SQLite Create Database
    • Send Mail in Python
    • Bash Scripting and Python
    • Violent Python Book
    • NLP in Python
    • Matplotlib In Python
    • Gray Hat Python: Security
    • Python Subprocess
    • Python Threading Timer
    • Python Threadpool
    • Python Statistics Module
    • How to Call a Function in Python?
    • Python Curl
    • JSON in Python
    • Python json.dumps
    • Python Turtle
    • Python Unit Test
    • pass Keyword in Python
    • Tokenization in Python
    • Random Module in Python
    • Python Multiprocessing
    • Python getattr
    • Collection Module in Python
    • Print Statement in Python
    • Python Countdown Timer
    • Python Context Manager
    • File Handling in Python
    • Python Event Handler
    • Python Print Table
    • Python Docstring
    • Python Dictionary Keys
    • Python Iterator Dictionary
    • Python Class Attributes
    • Python Dictionary Methods
    • Namedtuple Python
    • Namedtuple Python
    • Namedtuple Python
    • Python Class Constants
    • Python Validation
    • Python Switch Case
    • Python Rest Server
    • Python Yield vs Return
    • Python Pickle vs JSON
  • Tkinter
    • Tkinter Widgets
    • Python Tkinter Button
    • Python Tkinter Canvas
    • Tkinter Frame
    • Tkinter LabelFrame
    • Python Tkinter Label
    • Tkinter Scrollbar
    • Tkinter Listbox
    • Tkinter Spinbox
    • Tkinter Checkbutton
    • Tkinter Menu
    • Tkinter Menubutton
    • Tkinter OptionMenu
    • Tkinter Messagebox
    • Tkinter Grid
    • Python Tkinter Entry
    • Tkinter after
    • Tkinter Colors
    • Tkinter Font
    • Tkinter PhotoImage
    • Tkinter TreeView
    • Tkinter Notebook
    • Tkinter Bind
    • Tkinter Icon
    • Tkinter Window Size
    • Tkinter Color Chart
    • Tkinter Slider
    • Tkinter Calculator
  • Python 3
    • Python 3 Commands
    • Python 3 cheat sheet
  • Interview Question
    • Python Interview Questions And Answers

Related Courses

Python Certification Course

Programming Languages Courses

Angular JS Certification Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Python Certification Course Learn More