[Python] Parsing JSON Strings: Converting to Dictionaries and Lists

To handle text-based JSON data (such as data retrieved from Web APIs or configuration files) within a Python program, use the loads() function from the standard json library.

This converts a JSON format string into Python objects like dictionaries (dict) or lists (list), allowing you to freely extract data using keys and indices.

目次

Implementation Example: Parsing Product Catalog Data

In this example, we will parse a JSON string (simulating an API response containing smartphone catalog information) and extract specific information such as category, features, and product price.

Source Code

import json

# 1. Prepare a JSON format string
# (Usually retrieved via API response or file reading)
json_response = """
{
    "category": "Smartphone",
    "tags": ["5G", "OLED", "Dual Sim"],
    "products": [
        { "model": "Galaxy S25", "price": 120000, "in_stock": true },
        { "model": "Pixel 9", "price": 98000, "in_stock": false }
    ],
    "meta_info": null
}
"""

# 2. Convert the string to a Python object (dictionary) using json.loads()
# 'loads' stands for 'load string'
data = json.loads(json_response)

# Check the conversion result
print("--- Converted Data Type ---")
print(type(data))  # <class 'dict'>

print("\n--- Accessing Data ---")
# Access using dictionary keys
print(f"Category    : {data['category']}")

# Access using list indices
print(f"Tag 1       : {data['tags'][0]}")

# Accessing nested data
# data["products"] gets the list -> [0] gets the first element -> ["price"] gets the value
first_model_price = data['products'][0]['price']
print(f"Product Price: {first_model_price}")

# Check conversion of JSON null and boolean values
print(f"Stock Status : {data['products'][1]['in_stock']}") # false -> False
print(f"Meta Info    : {data['meta_info']}")             # null -> None

Execution Result

--- Converted Data Type ---
<class 'dict'>

--- Accessing Data ---
Category    : Smartphone
Tag 1       : 5G
Product Price: 120000
Stock Status : False
Meta Info    : None

Explanation

The Role of json.loads()

json.loads(string) takes a string that follows the JSON format, converts it into the corresponding Python data type, and returns it.

JSON and Python Type Mapping Table

JSON data types are automatically mapped to Python types as follows:

JSONPython
object ({...})dict (Dictionary)
array ([...])list (List)
stringstr
number (int/float)int or float
true / falseTrue / False
nullNone

Note: Difference Between loads and load

  • json.loads(string): Used when loading from a JSON formatted string (Load String).
  • json.load(file): Used when loading directly from a file object opened with open().
# Example of loading from a file
with open("data.json", "r") as f:
    data = json.load(f)
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次