JSON In Python

The purpose of this post is to introduce Python Json with examples in order to accomplish the learning objectives.

A JSON file can be used to store and exchange data.

JavaScript object notation is used to write JSON text.



Python JSON

The Python JSON package comes with a built-in package known as JSON, which can be used to work with JSON data.

You will need to import the Python JSON module as follows:

import json

Convert JSON to Python – JSON Parse

By executing json.loads(), you can parse a JSON string.

You will receive a Python dictionary as a result.

Python conversion from JSON:

Example: 

import json# some JSON: mrx = '{"name":"Harry", "age":19, "city":"San Francisco", "profession":"Football","postal code":"94016"}'# parse mrx: ample = json.loads(mrx)# You will get a Python dictionary as a result: print(ample["name"])

Convert Python to JSON

If you use the json.dumps() method, you can convert a Python object into a JSON string as we discuss Python JSON.

JSON conversion from Python:

Example: 

import json # Python object (dict): mrx = {'name': 'Harry', 'age': 19, 'city': 'San Francisco', 'profession': 'Football', 'postal code': '94016'} print("Dictionary Format:", mrx) print(type(mrx)) # Transform into JSON: ample = json.dumps(mrx) # You will get a JSON format as a result: print("JSON Format:", ample) print(type(ample))

In Python, you can convert the following types of objects into JSON strings:

  1. True
  2. False
  3. dict
  4. tuple
  5. string
  6. int
  7. float
  8. list
  9. None

Now make JSON strings from Python objects, and print their values:

Example: 

import jsonprint(json.dumps({'name': 'Harry', 'age': 19, 'country':'United States of America'})) print(json.dumps(['Football', 'Cricket', 'Hockey', 'Basketball'])) print(json.dumps(('Football', 'Cricket', 'Hockey', 'Basketball'))) print(json.dumps('Heyy Harry!')) print(json.dumps(19)) print(json.dumps(78.54)) print(json.dumps(True)) print(json.dumps(False)) print(json.dumps(None))

Python objects are converted to JSON (JavaScript) equivalents when you convert from Python to JSON:

PythonJSON
Truetrue
Falsefalse
DictObject
tupleArray
strstring
intNumber
floatNumber
listArray
Nonenull

Transform a Python object including all the legal data types:

Example: 

import jsonmrx = { "name": "Harry", "age": 19, "employed": False, "student": True, "siblings": ("Jane","Anthony"), "pets": None, "billionaires": [ {1: 'Bernard Arnault', 'net worth': '$164 billion'}, {2: 'Elon Musk', 'net worth': '$128 billion'}, {3: 'Gautam Adani', 'net worth': '$119 billion'}, {4: 'Bill Gates', 'net worth': '$109 billion'}, {5: 'Jeff Bezos', 'net worth': '$109 billion'} ] }# Transform into JSON: ample = json.dumps(mrx)# In JSON format, the result is: print(ample)

 


Order Result

json.dumps() method has parameters for sorting the keys – To sort the result, use the sort_keys parameter:

Example: 

import jsonmrx = { "name": "Harry", "age": 19, "employed": False, "student": True, "siblings": ("Jane","Anthony"), "pets": None, "billionaires": [ {'1': 'Bernard Arnault', 'net worth': '$164 billion'}, {'2': 'Elon Musk', 'net worth': '$128 billion'}, {'3': 'Gautam Adani', 'net worth': '$119 billion'}, {'4': 'Bill Gates', 'net worth': '$109 billion'}, {'5': 'Jeff Bezos', 'net worth': '$109 billion'} ] }# In alphabetical order, sort the result by key: ample = json.dumps(mrx, indent = 6, separators=(". "," == "), sort_keys=True)# In JSON format, the result is: print(ample)

Result Format

With no line breaks and indents, the example above prints a JSON string that is not very easy to read.

It is possible to simplify reading the results by using the parameters in the json.dumps() method.

To define the number of indents, use the indent parameter:

Example: 

import jsonmrx = { "name": "Harry", "age": 19, "employed": False, "student": True, "siblings": ("Jane","Anthony"), "pets": None, "billionaires": [ {1: 'Bernard Arnault', 'net worth': '$164 billion'}, {2: 'Elon Musk', 'net worth': '$128 billion'}, {3: 'Gautam Adani', 'net worth': '$119 billion'}, {4: 'Bill Gates', 'net worth': '$109 billion'}, {5: 'Jeff Bezos', 'net worth': '$109 billion'} ] }# To make the results easier to read, use six indents: ample = json.dumps(mrx, indent = 6)# In JSON format, the result is: print(ample)

Separators can also be defined; the default is (“,,:“), which means using a comma and a space to separate objects, and a colon and a space to separate keys and values.

To define the number of indents, use the indent parameter:

Example: 

import jsonmrx = { "name": "Harry", "age": 19, "employed": False, "student": True, "siblings": ("Jane","Anthony"), "pets": None, "billionaires": [ {1: 'Bernard Arnault', 'net worth': '$164 billion'}, {2: 'Elon Musk', 'net worth': '$128 billion'}, {3: 'Gautam Adani', 'net worth': '$119 billion'}, {4: 'Bill Gates', 'net worth': '$109 billion'}, {5: 'Jeff Bezos', 'net worth': '$109 billion'} ] }# Separate objects with . and a space, and separate keys from their values with a space, a ==, and a space: ample = json.dumps(mrx, indent = 6, separators=(". "," == "))# In JSON format, the result is: print(ample)

Python JSON Importance

Here are the key reasons why JSON is important in Python:

  1. JSON serves as a common data interchange format. It enables seamless communication between different systems and programming languages by providing a standardized way to represent and exchange data.
  2.  JSON is a lightweight format that uses a human-readable syntax. It consists of key-value pairs and supports arrays and nested structures. This simplicity makes it easy for humans to understand and work with JSON data.
  3. Python has built-in support for JSON with the json module, allowing easy conversion between JSON and Python data structures. This compatibility simplifies the process of serializing Python objects into JSON and deserializing JSON back into Python objects.
  4. Many web APIs (Application Programming Interfaces) use JSON as the preferred data format for sending and receiving data. Python developers can utilize the json module to interact with these APIs, making it convenient to consume and process JSON data from web services.
  5. JSON is commonly used for storing configuration settings and parameters in applications. It provides a structured and readable format to define and store application configurations, making it easier to manage and modify settings.
  6. JSON is often used for storing and persisting data. It allows developers to save complex data structures, such as dictionaries and lists, in a textual format that can be easily saved to files or databases. The JSON format’s simplicity and wide support make it a popular choice for data storage and retrieval.
  7. JSON’s widespread adoption and support across different programming languages and platforms enable seamless interoperability. Python applications can exchange JSON data with systems implemented in other languages, enabling integration and cooperation among diverse technologies.
Get the latest technical information delivered to your inbox by subscribing to our Newsletter.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *