JSON in Python (Part-15)

Posted by

JSON in Python

JSON (JavaScript Object Notation) is a lightweight data interchange format that’s easy for humans to read and write, and easy for machines to parse and generate. Python has a built-in module called json that can be used to work with JSON data.

Convert from JSON to Python

To convert JSON data to a Python object, you can use the json.loads() method, which parses a JSON string and returns a Python dictionary or list.

Example:

import json

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

# Convert JSON string to Python dictionary
python_dict = json.loads(json_string)

print(python_dict)
print(python_dict['name'])

Output

{'name': 'John', 'age': 30, 'city': 'New York'}
John

Convert from Python to JSON

To convert a Python object to a JSON string, you can use the json.dumps() method, which serializes a Python dictionary or list to a JSON formatted string.

Example:

import json

# Python dictionary
python_dict = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Convert Python dictionary to JSON string
json_string = json.dumps(python_dict)

print(json_string)

Output

{"name": "John", "age": 30, "city": "New York"}

Format & Order Results

The json.dumps() method has parameters to make the output more readable and to order the keys.

Example:

import json

# Python dictionary
python_dict = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Convert Python dictionary to JSON string with formatting
json_string = json.dumps(python_dict, indent=4, sort_keys=True)

print(json_string)

Output

{
    "age": 30,
    "city": "New York",
    "name": "John"
}

Example Code

Here is a complete example that demonstrates converting JSON data to a Python dictionary and vice versa, and formatting the JSON output.

import json

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

# Convert JSON string to Python dictionary
python_dict = json.loads(json_string)
print("Converted JSON to Python dictionary:")
print(python_dict)

# Access dictionary values
print("\nAccessing values from Python dictionary:")
print(f"Name: {python_dict['name']}")
print(f"Age: {python_dict['age']}")
print(f"City: {python_dict['city']}")

# Convert Python dictionary to JSON string
json_string = json.dumps(python_dict)
print("\nConverted Python dictionary to JSON string:")
print(json_string)

# Convert Python dictionary to formatted JSON string
json_string = json.dumps(python_dict, indent=4, sort_keys=True)
print("\nFormatted JSON string:")
print(json_string)

Convert Python Object to JSON

Python provides a built-in module called json to work with JSON data. This module allows you to convert Python objects to JSON format and vice versa.

Mapping Python Objects to JSON

Here’s a table that shows the conversion of Python objects to JSON types:

PythonJSON
dictObject
listArray
tupleArray
strString
intNumber
floatNumber
Truetrue
Falsefalse
Nonenull

Example Code

To convert a Python object into a JSON string, use the json.dumps() method.

import json

# Python object (dictionary)
x = {
    "name": "John",
    "age": 30,
    "married": True,
    "divorced": False,
    "children": ("Ann", "Billy"),
    "pets": None,
    "cars": [
        {"model": "BMW 230", "mpg": 27.5},
        {"model": "Ford Edge", "mpg": 24.1}
    ]
}

# Convert Python object to JSON string
json_string = json.dumps(x, indent=4)

# Print JSON string
print(json_string)

Output:

{
    "name": "John",
    "age": 30,
    "married": true,
    "divorced": false,
    "children": [
        "Ann",
        "Billy"
    ],
    "pets": null,
    "cars": [
        {
            "model": "BMW 230",
            "mpg": 27.5
        },
        {
            "model": "Ford Edge",
            "mpg": 24.1
        }
    ]
}

Explanation

  • dict: Converted to JSON object.
  • list and tuple: Converted to JSON array.
  • str: Converted to JSON string.
  • int and float: Converted to JSON number.
  • True: Converted to JSON true.
  • False: Converted to JSON false.
  • None: Converted to JSON null.

The json.dumps() method can also take several optional parameters:

  • indent: Defines the indentation level for pretty-printing.
  • sort_keys: If set to True, the output will be sorted by the dictionary keys.


Formatting JSON Results

When working with JSON in Python, you can use the json.dumps() method to convert Python objects into a JSON string. This method allows you to format the JSON output in a more readable way using various parameters.

Examples of Formatting

  1. Indentation:
    • You can use the indent parameter to define the number of spaces for indentation.
json.dumps(x, indent=4)

Separators:

  • The separators parameter allows you to specify how items are separated.
json.dumps(x, indent=4, separators=(". ", " = "))

Sorting Keys:

  • The sort_keys parameter sorts the dictionary keys in the output.
json.dumps(x, indent=4, sort_keys=True)

Example Code

Here’s an example Python dictionary and how you can format it using these parameters:

import json

# Python object (dictionary)
x = {
    "name": "John",
    "age": 30,
    "married": True,
    "divorced": False,
    "children": ("Ann", "Billy"),
    "pets": None,
    "cars": [
        {"model": "BMW 230", "mpg": 27.5},
        {"model": "Ford Edge", "mpg": 24.1}
    ]
}

# Format JSON with indentation
json_string_indent = json.dumps(x, indent=4)
print(json_string_indent)

# Format JSON with custom separators
json_string_separators = json.dumps(x, indent=4, separators=(". ", " = "))
print(json_string_separators)

# Format JSON with sorted keys
json_string_sorted = json.dumps(x, indent=4, sort_keys=True)
print(json_string_sorted)

Explanation of Parameters

  • indent: This parameter makes the JSON string output more readable by adding new lines and indentation. The value of indent specifies the number of spaces to use for each indentation level.
json.dumps(x, indent=4)

Output:

{
    "name": "John",
    "age": 30,
    "married": true,
    "divorced": false,
    "children": [
        "Ann",
        "Billy"
    ],
    "pets": null,
    "cars": [
        {
            "model": "BMW 230",
            "mpg": 27.5
        },
        {
            "model": "Ford Edge",
            "mpg": 24.1
        }
    ]
}

separators: This parameter allows you to change the default item and key-value separators. The default is (", ", ": ").

json.dumps(x, indent=4, separators=(". ", " = "))

Output:

{
    "name" = "John". 
    "age" = 30. 
    "married" = true. 
    "divorced" = false. 
    "children" = [
        "Ann". 
        "Billy"
    ]. 
    "pets" = null. 
    "cars" = [
        {
            "model" = "BMW 230". 
            "mpg" = 27.5
        }. 
        {
            "model" = "Ford Edge". 
            "mpg" = 24.1
        }
    ]
}

sort_keys: When this parameter is set to True, the JSON output will be sorted by key.

json.dumps(x, indent=4, sort_keys=True)

Output:

{
    "age": 30,
    "cars": [
        {
            "model": "BMW 230",
            "mpg": 27.5
        },
        {
            "model": "Ford Edge",
            "mpg": 24.1
        }
    ],
    "children": [
        "Ann",
        "Billy"
    ],
    "divorced": false,
    "married": true,
    "name": "John",
    "pets": null
}

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x