Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ JSON Processing | File I/O & Data Handling
Introduction to Python with Cursor

bookJSON Processing

メニューを表示するにはスワイプしてください

JSON (JavaScript Object Notation) is a lightweight text format for storing and sharing data, common in web apps, APIs, and configs. It's both human-readable and easy for machines to parse.

In Python, the built-in json module lets you convert between JSON and Python objects.

What JSON Looks Like

JSON is made of key-value pairs (like Python dictionaries) and lists of values.

  • Objects use curly braces {} with keys in double quotes;
  • Arrays use square brackets [].

Example:

{
  "name": "Alice",
  "age": 30,
  "hobbies": ["reading", "cycling"]
}

Working with JSON Data

Suppose we have a prepared file "data.json" with a user's name, age, and hobbies.

Reading and Printing Nicely

Open the file in read mode and use json.load() to convert it into a Python object. You can print it directly, or use json.dumps(..., indent=4)¡ to display it in a readable format.

Updating Values in JSON Data

After loading JSON into a Python dictionary, you can update it like any other dictionary. For example, modify the "age" value or append a new hobby to the "hobbies" list.

Writing Updated Data Back

After changes, open the file in write mode and use json.dump() to save the updated dictionary as JSON. Include the indent parameter to keep the file formatted and easy to read.

Handling Nested JSON Structures

JSON can include nested objects and arrays — dictionaries inside dictionaries or lists with multiple levels.

To access values, combine dictionary keys and list indexes. For example: user['address']['city'] retrieves the city inside the address object.

Summary

  • JSON is a lightweight and universal format for storing and sharing data;
  • Python's json module handles reading, writing, and converting JSON;
  • You can update JSON, format it for readability, and work with nested structures;
  • Understanding nested data access is key when working with real-world JSON files.
question mark

Which module is used to work with JSON data in Python?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 5.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 5.  2
some-alt