Formatting the Result with Python

Formatting the Result

Indentation

Indentation helps in making JSON data more readable by adding spaces to show the hierarchy and structure of the data.

Using the indent Parameter:

The indent parameter in json.dumps() controls the number of spaces used for indentation.

  • No Indentation (default): JSON output is in a compact form without extra spaces or line breaks.
  • With Indentation: Adds newlines and spaces to format the JSON output.

Example: 

import json
data = {
    "name": "Alice",
    "age": 30,
    "city": "Paris",
    "address": {
        "street": "123 Main St",
        "postal_code": "75000"
    },
    "hobbies": ["reading", "cycling"]
}
# Convert to JSON with indentation
json_string = json.dumps(data, indent=4)
print(json_string)
"""
Output: 
 {
    "name": "Alice",
    "age": 30,
    "city": "Paris",
    "address": {
        "street": "123 Main St",
        "postal_code": "75000"
    },
    "hobbies": [
        "reading",
        "cycling"
    ]
}
"""

Explanation:

  • indent=4: Adds 4 spaces of indentation for each level of nesting.
  • Indentation makes the JSON structure clear and easier to read.

Separators

The separators parameter allows you to customize the characters used to separate items and key-value pairs in the JSON output.

Using the separators Parameter:

  • (item_separator, key_separator): Tuple that defines how items and key-value pairs are separated.

Example: 

import json
data = {
    "name": "Alice",
    "age": 30,
    "city": "Paris"
}
# Convert to JSON with custom separators
json_string = json.dumps(data, separators=(',', ': '))
print(json_string)
"""
Output:
{"name": "Alice", "age": 30, "city": "Paris"}
"""

Explanation:

  • separators=(‘,’, ‘: ‘): Uses a comma followed by a space to separate items and a colon followed by a space to separate keys and values.
  • Customizing separators can improve the readability or compactness of the JSON output.

Sorting Keys

The sort_keys parameter sorts the keys of JSON objects in alphabetical order.

Using the sort_keys Parameter:

Example: 

import json
data = {
    "name": "Alice",
    "city": "Paris",
    "age": 30
}
# Convert to JSON with sorted keys
json_string = json.dumps(data, sort_keys=True, indent=2)
print(json_string)
"""
Output:
{
  "age": 30,
  "city": "Paris",
  "name": "Alice"
}
"""

Explanation:

  • sort_keys=True: Sorts dictionary keys in alphabetical order.
  • Useful for consistent and predictable JSON output, especially when debugging or comparing data.

Ensuring ASCII Characters

By default, json.dumps() escapes non-ASCII characters. You can control this behavior with the ensure_ascii parameter.

Using the ensure_ascii Parameter:

  • ensure_ascii=True: Escapes non-ASCII characters, ensuring that the output is ASCII-only.
  • ensure_ascii=False: Allows non-ASCII characters to be included in the output as-is.

Example: 

import json
data = {
    "name": "Alice",
    "city": "München"  # Non-ASCII character
}
# Convert to JSON with non-ASCII characters escaped
json_string = json.dumps(data, ensure_ascii=True)
print(json_string)  # {"name": "Alice", "city": "München"}
"""
Output:
{"name": "Alice", "city": "München"}
"""

Explanation:

  • ensure_ascii=True: Converts non-ASCII characters into escape sequences.
  • ensure_ascii=False: Outputs non-ASCII characters directly, which is more human-readable but might not be suitable for all systems.

Compact vs. Pretty Printing

You can choose between compact JSON (no extra spaces) and pretty-printed JSON (with indentation and spaces).

Compact JSON: 

import json
data = {
    "name": "Alice",
    "age": 30,
    "city": "Paris"
}
# Compact JSON
json_string = json.dumps(data, separators=(',', ':'))
print(json_string)
"""
Output:
{"name":"Alice","age":30,"city":"Paris"}
"""

Pretty-Printed JSON: 

import json
data = {
    "name": "Alice",
    "age": 30,
    "city": "Paris"
}
# Pretty-printed JSON
json_string = json.dumps(data, indent=4, separators=(',', ': '))
print(json_string)
"""
Output:
{
    "name": "Alice",
    "age": 30,
    "city": "Paris"
}
"""

 Explanation:

  • Compact JSON: Omits extra spaces to minimize size.
  • Pretty-printed JSON: Includes indentation and spaces to improve readability.

Custom JSON Encoding

For custom data types or special formatting needs, you can use the default parameter to specify a function for encoding objects.

Example with Custom Encoder: 

import json
from datetime import datetime
# Custom encoder function
def custom_encoder(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError("Type not serializable")
data = {
    "name": "Alice",
    "birthdate": datetime(1994, 7, 14)
}
# Convert to JSON with custom encoder
json_string = json.dumps(data, default=custom_encoder, indent=2)
print(json_string)
"""
Output:
{
  "name": "Alice",
  "birthdate": "1994-07-14T00:00:00"
}
"""

Explanation:

  • default=custom_encoder: Uses the custom_encoder function to handle non-serializable objects, such as datetime.
  • Allows for customized serialization of complex or non-standard data types.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *