Python JSONJSON stands for JavaScript Object Notation, which is a widely used data format for data interchange on the web. JSON is the ideal format for organizing data between a client and a server. Its syntax is similar to the JavaScript programming language. The main objective of JSON is to transmit the data between the client and the web server. It is easy to learn and the most effective way to interchange the data. It can be used with various programming languages such as Python, Perl, Java, etc. JSON mainly supports 6 types of data type In JavaScript:
JSON is built on the two structures:
JSON data representation is similar to the Python dictionary. Below is an example of JSON data: Working with Python JSONPython provides a module called json. Python supports standard library marshal and pickle module, and JSON API behaves similarly as these library. Python natively supports JSON features. The encoding of JSON data is called Serialization. Serialization is a technique where data transforms in the series of bytes and transmitted across the network. The deserialization is the reverse process of decoding the data that is converted into the JSON format. This module includes many built-in functions. Let's have a look at these functions: Output: ['JSONDecodeError', 'JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_default_decoder', '_default_encoder', 'codecs', 'decoder', 'detect_encoding', 'dump', 'dumps', 'encoder', 'load', 'loads', 'scanner'] In this section, we will learn the following methods:
Serializing JSONSerialization is the technique to convert the Python objects to JSON. Sometimes, computer need to process lots of information so it is good to store that information into the file. We can store JSON data into file using JSON function. The json module provides the dump() and dumps() method that are used to transform Python object. Python objects are converted into the following JSON objects. The list is given below:
Writing JSON Data into File Python provides a dump() function to transmit(encode) data in JSON format. It accepts two positional arguments, first is the data object to be serialized and second is the file-like object to which the bytes needs to be written. Let's consider the simple serialization example: Output: {"Name" : "Peter", "Roll_no" : "0090014" , "Grade" : "A", "Age" : 20, "Subject" : ["Computer Graphics", "Discrete Mathematics", "Data Structure"] } In the above program, we have opened a file named data.json in writing mode. We opened this file in write mode because if the file doesn't exist, it will be created. The json.dump() method transforms dictionary into JSON string.
The dumps() function is used to store serialized data in the Python file. It accepts only one argument that is Python data for serialization. The file-like argument is not used because we aren't not writing data to disk. Let's consider the following example: Output: {"Name": "Peter", "Roll_no": "0090014", "Grade": "A", "Age": 20} JSON supports primitive data types, such as strings and numbers, as well as nested list, tuples and objects. Output: ["Welcome", "to", "javaTpoint"] ["Welcome", "to", "javaTpoint"] "Hello" 1234 23.572 true false null Deserializing JSONDeserialization is the process to decode the JSON data into the Python objects. The json module provides two methods load() and loads(), which are used to convert JSON data in actual Python object form. The list is given below:
The above table shows the inverse of the serialized table but technically it is not a perfect conversion of the JSON data. It means that if we encode the object and decode it again after sometime; we may not get the same object back. Let's take real-life example, one person translates something into Chinese and another person translates back into English, and that may not be exactly translated. Consider the simple example: Output:
The load() function is used to deserialize the JSON data to Python object from the file. Consider the following example: Output: {'Name': 'Peter', 'Roll_no': '0090014', 'Grade': 'A', 'Age': 20} In the above program, we have encoded Python object in the file using dump() function. After that we read JSON file using load() function, where we have passed read_file as an argument. The json module also provides loads() function, which is used to convert JSON data to Python object. It is quite similar to the load() function. Consider the following example: Output: ['Mathew', 'Peter', [10, 32.9, 80], {'Name': 'Tokyo'}] json.load() vs json.loads()The json.load() function is used to load JSON file, whereas json.loads() function is used to load string. json.dump() vs json.dumps()The json.dump() function is used when we want to serialize the Python objects into JSON file and json.dumps() function is used to convert JSON data as a string for parsing and printing. Python Pretty Print JSONSometimes we need to analyze and debug a large amount of JSON data. It can be done by passing additional arguments indent and sort_keys in json.dumps() and json.dump() methods. Note: Both dump() and dumps() functions accept indent and short_keys arguments.Consider the following example: Output: { "Age": 23, "City": "English", "Name": "Andrew", "Number": 90014, "Subject": [ "Data Structure", "Computer Graphics", "Discrete mathematics" ] } In the above code, we have provided the 5 spaces to the indent argument and the keys are sorted in ascending order. The default value of indent is None and the default value of sort_key is False. Encoding and DecodingEncoding is the technique for transforming the text or values into an encrypted form. Encrypted data can only be used by the preferred user by decoding it. Encoding is also known as serialization and decoding is also called deserialization. Encoding and decoding are done for JSON(object) format. Python provides a popular package for such operations. We can install it on Windows by the following command: Encoding - The demjson package provides encode() function that is used to convert the Python object into a JSON string representation. The syntax is given below: Example:1 - Encoding using demjson package Output: [{"Age":20,"Name":"Peter","Subject":"Electronics"}] Decoding-The demjson module provides decode() function, which is used to convert JSON object into Python format type. The syntax is given below: Output: ['Peter', 'Smith', 'Ricky', 'Hayden'] In this tutorial, we have learned about the Python JSON. JSON is the most effective way to transmit data between the client and the web server. Next TopicPython Itertools
|
Python tutorial provides basic and advanced concepts of Python.
Vue.js is an open-source progressive JavaScript framework
HTML refers to Hypertext Markup Language. HTML is the gateway ...
Java is an object-oriented, class-based computer-programming language.
PHP is an open-source,interpreted scripting language.
Spring is a lightweight framework.Spring framework makes ...
JavaScript is an scripting language which is lightweight and cross-platform.
CSS refers to Cascading Style Sheets...
jQuery is a small and lightweight JavaScript library. jQuery ...
SQL is used to perform operations on the records stored in the database.
C programming is considered as the base for other programming languages.
JavaScript is an scripting language which is lightweight and cross-platform.
Vue.js is an open-source progressive JavaScript framework
ReactJS is a declarative, efficient, and flexible JavaScript library.
jQuery is a small and lightweight JavaScript library. jQuery ...
Node.js is a cross-platform environment and library for running JavaScript app...
TypeScript is a strongly typed superset of JavaScript which compiles to plain JavaScript.
Angular JS is an open source JavaScript framework by Google to build web app...
JSON is lightweight data-interchange format.
AJAX is an acronym for Asynchronous JavaScript and XML.
ES6 or ECMAScript 6 is a scripting language specification ...
Angular 7 is completely based on components.
jQuery UI is a set of user interface interactions built on jQuery...
Python tutorial provides basic and advanced concepts of Python.
Java is an object-oriented, class-based computer-programming language.
Node.js is a cross-platform environment and library for running JavaScript app...
PHP is an open-source,interpreted scripting language.
Go is a programming language which is developed by Google...
C programming is considered as the base for other programming languages.
C++ is an object-oriented programming language. It is an extension to C programming.
C# is a programming language of .Net Framework.
Ruby is an open-source and fully object-oriented programming language.
JSP technology is used to create web application just like Servlet technology.
The JSTL represents a set of tags to simplify the JSP development.
ASP.NET is a web framework designed and developed by Microsoft.
Perl is a cross-platform environment and library for running JavaScript...
Scala is an object-oriented and functional programming language.
VBA stands for Visual Basic for Applications.
Spring is a lightweight framework.Spring framework makes ...
Spring Boot is a Spring module that provides the RAD feature...
Django is a Web Application Framework which is used to develop web applications.
Servlet technology is robust and scalable because of java language.
The Struts 2 framework is used to develop MVC based web applications.
Hibernate is an open source, lightweight, ORM tool.
Solr is a scalable, ready-to-deploy enterprise search engine.
SQL is used to perform operations on the records stored in the database.
MySQL is a relational database management system based...
Oracle is a relational database management system.
SQL Server is software developed by Microsoft.
PostgreSQL is an ORDBMS.
DB2 is a database server developed by IBM.
Redis is a No SQL database which works on the concept of key-value pair.
SQLite is embedded relational database management system.
MongoDB is a No SQL database. It is an document-oriented database...
Memcached is a free, distributed memory object caching system.
Hibernate is an open source, lightweight, ORM tool.
PL/SQL is a block structured language that can have multiple blocks in it.
DBMS Tutorial is software that is used to manage the database.
Spark is a unified analytics engine for large-scale data processing...
IntelliJ IDEA is an IDE for Java Developers which is developed by...
Git is a modern and widely used distributed version control system in the world.
GitHub is an immense platform for code hosting.
SVN is an open-source centralized version control system.
Maven is a powerful project management tool that is based on POM.
Jsoup is a java html parser.
UML is a general-purpose, graphical modeling language.
RESTful Web Services are REST Architecture based Web Services.
Postman is one testing tools which is used for API testing.
JMeter is to analyze the performance of web application.
Jenkins builds and tests our software projects.
SEO stands for Search Engine Optimization.
MATLAB is a software package for mathematical computation, visualization...
Unity is an engine for creating games on multiple platforms.
Hadoop is an open source framework.
Pig is a high-level data flow platform for executing Map Reduce programs of Hadoop.
Spark is a unified analytics engine for large-scale data processing...
Spring Cloud is a framework for building robust cloud applications.
Spring Boot is a Spring module that provides the RAD feature...
AI is one of the fascinating and universal fields of Computer.
Cloud computing is a virtualization-based technology.
AWS stands for Amazon Web Services which uses distributed IT...
Microsoft Azure is a cloud computing platform...
IoT stands for Internet of Things...
Spring Cloud is a framework for building robust cloud applications.
Email:jjw.quan@gmail.com