+91 81900 98289

Python JSON

This Python JSON lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

JSON is a text format for objects and lists. json.dumps turns a Python dict into text. json.loads turns text back into a dict.

JSON uses true, false, and null. Python uses True, False, and None. The json module translates them.

Example 1: Start here

dumps is for text. dump, without the s, writes to a file.

import json # load a tool that comes with Python payload = {"name": "Meera", "active": True} # a dictionary; each key has one value text = json.dumps(payload) # the value written as JSON text print(text) print(json.loads(text)["name"])

Example 2: Dump to text

dumps turns a dictionary into a JSON string.

import json # load a tool that comes with Python print(json.dumps({"city": "Chennai", "seats": 24}))

Example 3: Load it back

loads reads JSON text and returns a dictionary.

import json # load a tool that comes with Python data = json.loads('{"city": "Chennai"}') # the value read from JSON text print(data["city"])

Example 4: A list in JSON

A JSON array becomes a Python list.

import json # load a tool that comes with Python print(json.loads('["Python", "SQL"]'))
dumps is for text. dump, without the s, writes to a file.
Call Now 81900 98289