Python JSON

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. Python provides a built-in module called json to work with JSON data.


JSON Syntax

JSON data is written in key/value pairs. Keys are strings, and values can be strings, numbers, objects, arrays, true, false, or null.

Example of JSON:

{
  "name": "John",
  "age": 30,
  "city": "New York"
}




Parsing JSON

To parse a JSON string into a Python dictionary, you can use the json.loads() method.

Example:

import json

# JSON string
json_data = '{"name": "John", "age": 30, "city": "New York"}'

# Parse JSON string into Python dictionary
data = json.loads(json_data)

print(data["name"])  # Output: John




Converting to JSON

To convert a Python dictionary into a JSON string, use the json.dumps() method.

Example:

import json

# Python dictionary
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Convert dictionary to JSON string
json_data = json.dumps(data)

print(json_data)  # Output: {"name": "John", "age": 30, "city": "New York"}




Reading JSON from a File

To read JSON data from a file, you can use the json.load() method.

Example:

import json

# Read JSON data from a file
with open('data.json', 'r') as file:
    data = json.load(file)

print(data["name"])  # Output depends on content of data.json




Writing JSON to a File

To write JSON data to a file, use the json.dump() method.

Example:

import json

# Python dictionary
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Write JSON data to a file
with open('data.json', 'w') as file:
    json.dump(data, file)




Working with Nested JSON

JSON data can be nested, meaning objects can contain other objects or arrays. You can parse and access nested JSON data similarly.

Example:

import json

# JSON string
json_data = '''
{
  "name": "John",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "New York"
  },
  "phoneNumbers": [
    {"type": "home", "number": "212-555-1234"},
    {"type": "office", "number": "646-555-4567"}
  ]
}
'''

# Parse JSON string
data = json.loads(json_data)

print(data["address"]["city"])  # Output: New York
print(data["phoneNumbers"][1]["number"])  # Output: 646-555-4567




Python Labs

Scroll to Top