← Back to Blog

Python and JSON: Complete Guide to json Module

Master JSON in Python with the json module. Learn to parse, generate, and manipulate JSON data with practical examples and best practices.

Big JSON Team13 min readprogramming
B

Big JSON Team

Technical Writer

Expert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.

13 min read

The Python json Module

Python's built-in json module makes working with JSON data simple and efficient.

Parsing JSON

json.loads() - Parse JSON String

import json

json_string = '{"name": "Alice", "age": 30}'

data = json.loads(json_string)

print(data['name']) # "Alice"

print(type(data)) # <class 'dict'>

json.load() - Read from File

import json

with open('data.json', 'r') as file:

data = json.load(file)

print(data)

Generating JSON

json.dumps() - Convert to JSON String

import json

data = {

"name": "Bob",

"age": 25,

"active": True

}

json_string = json.dumps(data)

print(json_string)

# {"name": "Bob", "age": 25, "active": true}

Pretty Printing

json_string = json.dumps(data, indent=2)

print(json_string)

# {

# "name": "Bob",

# "age": 25,

# "active": true

# }

json.dump() - Write to File

with open('output.json', 'w') as file:

json.dump(data, file, indent=2)

Type Mapping

| Python | JSON |

|--------|------|

| dict | object |

| list, tuple | array |

| str | string |

| int, float | number |

| True | true |

| False | false |

| None | null |

Common Options

Sort Keys

json.dumps(data, sort_keys=True)

Handle Non-Serializable Objects

from datetime import datetime

def json_serial(obj):

if isinstance(obj, datetime):

return obj.isoformat()

raise TypeError(f"Type {type(obj)} not serializable")

data = {"timestamp": datetime.now()}

json.dumps(data, default=json_serial)

Error Handling

try:

data = json.loads(invalid_json)

except json.JSONDecodeError as e:

print(f"Error: {e}")

print(f"Line {e.lineno}, Column {e.colno}")

Working with APIs

import requests

import json

response = requests.get('https://api.example.com/users')

data = response.json() # Automatically parses JSON

for user in data['users']:

print(user['name'])

Best Practices

  • Always use with statement for file operations
  • Handle JSONDecodeError exceptions
  • Use indent for readable output
  • Validate data before parsing
  • Use UTF-8 encoding for files
  • Conclusion

    Python's json module is powerful and easy to use. Master json.loads(), json.dumps(), and file operations for all your JSON needs!

    Share:

    Related Articles

    Read in other languages