Information retrieved from the internet is often passed simply as a "string."
Even if it looks like a dictionary, it is actually just a "chunk of text," making it difficult to use as-is.
This is where Python's json.loads() function comes in handy.
By using this function, you can convert JSON data represented as a string into a format that can be manipulated in Python.
It is essentially like a tool that opens a "box" of wrapped data (a string) to extract the contents.
What is json.loads()?
json.loads() is a function used to convert a JSON-formatted string (str type) into Python data types (such as dictionaries or lists).
Breaking down the meaning of the name:
load: to read
s: string
In other words, it has the role of "reading a string and making it usable as Python data."
Practical usage example:import json json_str = '"name": "Momo", "age": 18' data = json.loads(json_str) print(data) # 'name': 'Momo', 'age': 18 print(data["name"]) # Momo
In this example, json_str is a JSON-formatted string.
When you read this with json.loads(), it becomes usable as a Python dictionary (dict).
Points to note about JSON format (to prevent errors)
There are a few points to keep in mind when using json.loads(). A common pitfall for beginners is the difference in quotes.
For example, the following code will result in an error:bad_json = "'name': 'Momo'" # シングルクォートを使用 data = json.loads(bad_json) # ❌ エラー!
The cause of this error is the rule that JSON requires double quotes (") for strings.
While Python allows single quotes, they are not permitted in JSON.
Incorrect format:
'key': 'value' ← シングルクォートはNG
Correct format:
"key": "value" ← ダブルクォートを使用
Handling list-formatted JSON
The JSON format is often used not only for dictionaries but also for list-formatted data.
Below is an example of a JSON string containing multiple dictionaries:
json_str = '["name": "Momo", "name": "Sakura"]' data = json.loads(json_str) print(data[0]["name"]) # Momo
As shown, when you read a list-formatted JSON string, it is converted into a Python list.
Since the elements inside can each be treated as dictionaries, you can manipulate the data flexibly.
This format often appears when receiving data such as multiple user profiles or product lists from a Web API.
Summary
json.loads() is a fundamental and essential tool for converting JSON-formatted string data into objects that can be used in Python.
To summarize the key points:
Converts JSON strings (str type) into Python objects (dict or list)
In JSON, double quotes (") are mandatory
Can also handle JSON in list format
By mastering these basics, you will find them useful in a wide range of situations, such as processing API responses and reading files!