Overview

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format, independent of programming languages. It structures data using key-value pairs, making it human-readable and machine-parse able.

Basic JSON structure: Example:

{
  "name": "Alice",
  "age": 25,
  "skills": ["Python", "JavaScript", "SQL"],
  "is_active": true
}

JSON vs Python Dictionary

JSON and Python dictionaries share similarities but differ in key aspects.

FeatureJSONPython Dictionary
KeysMust be stringsAny hashable type
QuotesDouble quotes onlySingle or double quotes
Booleanstrue, falseTrue, False
Null valuesnullNone
Trailing commasNot allowedAllowed

Valid JSON Rules

JSON adheres to strict formatting unlike YAML’s behavior which can vary with different versions and evolving specifications.

  • Data Types:
    • Strings (double-quoted)
    • Numbers (integer/float)
    • Booleans (true/false)
    • null
    • Objects (key-value pairs)
    • Arrays (ordered lists)
  • Key Rules:
    • Strings must use double quotes.
    • Trailing commas are prohibited.
    • Comments are not allowed.
    • Keys must be strings.
{
  "valid_string": "Hello World",
  "valid_number": 42,
  "valid_boolean": true,
  "valid_null": null,
  "valid_array": [1, 2, 3],
  "valid_object": {"nested": "value"}
}

Reading and Writing JSON in Python

Python’s json module provides four core functions:

  • For Strings:
    • json.loads(): Converts JSON string to Python object.
    • json.dumps(): Converts Python object to JSON string.
  • For Files:
    • json.load(): Reads JSON from a file.
    • json.dump(): Writes JSON to a file.

Examples

Reading JSON:

import json
# From string
json_string = '{"name": "Bob", "age": 30}'
data = json.loads(json_string)
print(data["name"])  # Output: Bob
 
# From file
with open('data.json', 'r') as file:
    data = json.load(file)

Writing JSON:

import json
# To string
data = {"name": "Charlie", "age": 35}
json_string = json.dumps(data, indent=2)
print(json_string)
 
# To file
with open('output.json', 'w') as file:
    json.dump(data, file, indent=2)

The indent parameter enhances readability by adding whitespace.

Common Errors and Best Practices

  • Encoding Issues: Specify encoding='utf-8' for files with non-ASCII characters.

    with open('data.json', 'r', encoding='utf-8') as file:
        data = json.load(file)
  • Common Mistakes:

    • Trailing commas: JSON disallows them, unlike Python dictionaries.

      # Invalid JSON
      bad_json = '{"name": "Alice", "age": 25,}'
      # Valid dictionary in Python
      good_dict = {"name": "Alice", "age": 25,}
    • Quote types: JSON requires double quotes.

      # Invalid JSON
      bad_json = "{'name': 'Alice'}"
      # Valid JSON        
      good_json = '{"name": "Alice"}'

Applications of JSON

JSON is prevalent in:

REST APIs: Data exchange between services
Configuration files: Application settings
Inter-service communication: Microservices messaging
Data storage: NoSQL databases (MongoDB)