Skip to content

JSON With Python

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. It is a common data format with diverse uses in electronic data interchange, including web services and configuration files.

Parsing JSON:

        
import json

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

# Parsing JSON
parsed_data = json.loads(json_data)
        
    

Converting to JSON:

        
# Python dictionary
person = {"name": "Alice", "age": 25, "city": "London"}

# Converting to JSON
json_person = json.dumps(person)
        
    

JSON Strings:

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

Formatting the JSON:

        
# Formatted JSON string
formatted_json = json.dumps(parsed_data, indent=2)
        
    

Usage of Separators:

        
# Custom separators
custom_json = json.dumps(parsed_data, separators=(",", ":"))
        
    

Sorting:

        
# Sorting keys
sorted_json = json.dumps(parsed_data, indent=2, sort_keys=True)
        
    

Key Points:

  • JSON is a common data interchange format.
  • Python's json module is used for working with JSON data.
  • json.loads() is used to parse JSON strings.
  • json.dumps() converts Python objects to JSON strings.
  • Formatting options include indent, separators, and sort_keys.