Parsing JSON – Converting JSON to Python

Parsing JSON – Converting JSON to Python

JSON Types and Their Python Equivalents

JSON data can be converted into several Python types:

  • JSON Object: { “key”: “value” } → Python Dictionary: { “key”: “value” }
  • JSON Array: [ “value1”, “value2” ] → Python List: [ “value1”, “value2” ]
  • JSON String: “string” → Python String: “string”
  • JSON Number: 123 or 123.45 → Python Integer or Float: 123 or 123.45
  • JSON Boolean: true/false → Python Boolean: True/False
  • JSON Null: null → Python None: None

Basic JSON Decoding

You use the json.loads() function to convert a JSON string into a Python object. Here’s a basic example:

Example: 

import json
# JSON string
json_string = '{"name": "Alice", "age": 30, "city": "Paris"}'
# Convert JSON to Python object
data = json.loads(json_string)
print(data)         # {'name': 'Alice', 'age': 30, 'city': 'Paris'}
print(type(data))   # <class 'dict'>

Explanation:

  • json.loads() takes a JSON-formatted string and returns a Python dictionary.
  • The JSON string’s keys and values are mapped to dictionary keys and values.

Handling Nested JSON Objects

JSON can contain nested structures, such as objects within objects or arrays within objects. json.loads() handles these nested structures seamlessly.

Example: 

import json
# Nested JSON string
json_string = '''
{
    "name": "Alice",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Paris"
    },
    "hobbies": ["reading", "cycling"]
}
'''
# Convert JSON to Python object
data = json.loads(json_string)
print(data)
# Output: {'name': 'Alice', 'age': 30, 'address': {'street': '123 Main St', 'city': 'Paris'}, 'hobbies': ['reading', 'cycling']}

Explanation:

  • The JSON object contains a nested object (address) and a nested array (hobbies).
  • These nested structures are converted to nested dictionaries and lists in Python.

Converting JSON Arrays

JSON arrays are converted to Python lists. Arrays can contain multiple data types, including other arrays or objects.

Example: 

import json
# JSON array string
json_string = '[1, 2, 3, {"name": "Alice"}, [4, 5]]'
# Convert JSON to Python object
data = json.loads(json_string)
print(data)
# Output: [1, 2, 3, {'name': 'Alice'}, [4, 5]]
print(type(data))  # <class 'list'>

Explanation:

  • The JSON array is converted to a Python list.
  • The list can contain integers, dictionaries, and other lists.

Handling JSON with Custom Data Types

If your JSON contains custom data types, you may need to handle them explicitly during parsing. For example, if a JSON string contains dates or other special objects, you can use the object_hook parameter of json.loads() to customize the decoding process.

Example with Custom Data Hook: 

import json
from datetime import datetime
# JSON string with a date
json_string = '{"name": "Alice", "birthdate": "1994-07-14"}'
# Custom function to convert JSON data
def custom_decoder(dct):
    if 'birthdate' in dct:
        dct['birthdate'] = datetime.strptime(dct['birthdate'], '%Y-%m-%d')
    return dct
# Convert JSON to Python object with custom decoding
data = json.loads(json_string, object_hook=custom_decoder)
print(data)
# Output: {'name': 'Alice', 'birthdate': datetime.datetime(1994, 7, 14, 0, 0)}
print(type(data['birthdate']))  # <class 'datetime.datetime'>

Explanation:

  • The custom_decoder function converts the birthdate string into a datetime object.
  • The object_hook parameter allows custom processing of JSON objects.

Error Handling During Decoding

When parsing JSON, you may encounter errors if the JSON string is malformed. It’s important to handle these errors to ensure your program can deal with unexpected data.

Example of Error Handling: 

import json
# Malformed JSON string
json_string = '{"name": "Alice", "age": 30, "city": "Paris"'
try:
    # Attempt to convert to Python object
    data = json.loads(json_string)
except json.JSONDecodeError as e:
    print(f"JSON decoding error: {e}")

 Explanation:

  • json.JSONDecodeError is raised if the JSON string is not properly formatted.
  • Handling this exception allows your program to continue running or provide informative feedback.

Working with JSON from Files

You can read JSON data from files using json.load(), which works similarly to json.loads() but reads from a file object.

Example of Reading from a File: 

import json
# JSON file reading
with open('data.json', 'r') as file:
    data = json.load(file)
print(data)

Explanation:

  • json.load() reads JSON data from a file and converts it into a Python object.
  • Ensure that the file contains valid JSON data.

Laisser un commentaire

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