ホーム 暮らし What is Python's json.loads()?

What is Python's json.loads()?

三浦 拓海 三浦 拓海 • 更新: • 公開: • 読了約 8 分
目次

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()?

nf32ecd5f4822

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!

同じカテゴリの記事

三浦 拓海
コンテンツディレクター 三浦 拓海
プロフィールを見る →

映画と連続ドラマの公開情報を追う担当。配給会社のプレスシートと公式サイトの発表日を確認したうえで執筆します。

おすすめの関連記事