LANGUAGE & SYNTAX · PYTHON

16 · JSON & CSV

JSON and CSV are common formats for exchanging data between systems.

JSON:

  • structured data
  • key + value
  • nested data supported
  • common in APIs

CSV:

  • rows + columns
  • similar to spreadsheet
  • simple tabular data

1. JSON Format

{
    "order_id": 1001,
    "customer": "Apple",
    "product": "Copper",
    "quantity": 10
}

JSON uses key-value pairs.

2. Python Dictionary vs JSON

Python:

order = {
    "order_id": 1001,
    "customer": "Apple",
    "is_active": True
}

JSON:

{
    "order_id": 1001,
    "customer": "Apple",
    "is_active": true
}

Important: Python uses:

True
False
None

JSON uses:

true
false
null

3. import json

import json

Python's standard library includes JSON support.

4. json.loads()

Converts JSON text into Python data.

text = '''
{
    "order_id": 1001,
    "product": "Copper"
}
'''
order = json.loads(text)
print(order["product"])

Output:

Copper

5. json.dumps()

Converts Python data into JSON text.

order = {
    "order_id": 1001,
    "product": "Copper"
}
text = json.dumps(order)

6. Pretty JSON

text = json.dumps(
    order,
    indent=2
)

indent makes JSON easier to read.

7. Read JSON File

Example file: order.json

{
    "order_id": 1001,
    "product": "Copper"
}
import json
with open(
    "order.json",
    "r",
    encoding="utf-8"
) as file:
    order = json.load(file)

8. Write JSON File

import json
order = {
    "order_id": 1001,
    "product": "Copper"
}
with open(
    "order.json",
    "w",
    encoding="utf-8"
) as file:
    json.dump(
        order,
        file,
        indent=2
    )

9. JSON Nested Data

order = {
    "order_id": 1001,
    "customer": {
        "id": "C01",
        "name": "Apple"
    }
}
customer_name = order["customer"]["name"]

Result:

Apple

10. JSON List

data = {
    "orders": [
        {
            "id": 1001,
            "product": "Copper"
        },
        {
            "id": 1002,
            "product": "Aluminum"
        }
    ]
}
first_order = data["orders"][0]

11. CSV Format

order_id,customer,product,quantity
1001,Apple,Copper,10
1002,Tesla,Aluminum,20

Each line is a row.

Values are separated by commas.

12. import csv

import csv

13. Read CSV

import csv
with open(
    "orders.csv",
    "r",
    encoding="utf-8"
) as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Possible output:

[
    "1001",
    "Apple",
    "Copper",
    "10"
]

14. csv.DictReader

Reads each CSV row as a dictionary.

import csv
with open(
    "orders.csv",
    "r",
    encoding="utf-8"
) as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row["product"])

Output:

Copper
Aluminum

15. Write CSV

import csv
with open(
    "orders.csv",
    "w",
    newline="",
    encoding="utf-8"
) as file:
    writer = csv.writer(file)
    writer.writerow([
        "order_id",
        "product",
        "quantity"
    ])
    writer.writerow([
        1001,
        "Copper",
        10
    ])

16. csv.DictWriter

import csv
fields = [
    "order_id",
    "product",
    "quantity"
]
with open(
    "orders.csv",
    "w",
    newline="",
    encoding="utf-8"
) as file:
    writer = csv.DictWriter(
        file,
        fieldnames=fields
    )
    writer.writeheader()
    writer.writerow({
        "order_id": 1001,
        "product": "Copper",
        "quantity": 10
    })

17. JSON vs CSV

JSONCSV
APIs
nested data
key-value structure
configuration
spreadsheet-like data
rows and columns
simple export/import
reporting
↑