python-json

Introduction to Python JSON with Examples

In this article you will learn about Python JSON.

Python JSON – Before moving ahead let’s know a little bit about Python Module

JSON – It is Python built-in package, which is used in Python to work with data related to JSON. JSON is text and written in javascript format.

— To use JSON, import JSON.

Example 1- To use JSON, import JSON.

import json

Parse JSON – Convert from JSON to Python – A JSON string can be parsed by using json.loads(). It will return output as Python Dictionary.

Example 2- Convert JSON in Python.

import json

x = '{"name" :  "Alex", "Add" : "NYC", "ID" : "123"}'
z = json.loads(x)

print(z['Add'])
python-json

Explanation – As shown clearly, it converted data from JSON to Python then returned specified value of a key (Add).

Convert from Python to JSON – A Python object can be converted into JSON string by using json.dumps() method.

Example 3- Convert from Python object to Json object.

import json
 
x = {"name" :  "Alex", "Add" : "NYC", "ID" : "123"}
z = json.dumps(x)

print(z) 
python-json

Explanation – As shown clearly, it converted data from Python to JSON then returned whole dictionary.

A Python object can be converted into the various types of JSON string: dict list, tuple, string, int, float, True, False, None.

Example 4- Convert Python object into Json string.

import json

x = {'name' :  'Alex', 'Add' : 'NYC', 'ID' : 123}
z = json.dumps(x)

print(z)
python-json

Explanation – As shown clearly, it converted the Python dict list into JSON string then returned the whole dictionary.

If you find anything incorrect in the above-discussed topic and have any further questions, please comment down below.

Like us on

Recent Post

Popular Post

Top Articles

Archives
Categories

Share on