Python处理JSON文件的完整流程(读取、解析、修改和保存)

作者:

文章目录
  • JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。以下是 JSON 文件的完整定义方法和规范。本文还介绍了使用Python处理JSON文件的完整流程,包括读取、解析、修改和保存JSON数据的方法。
  • 目录
    • 概述
    • 1 JSON文件
      • 1.1 JSON文件定义
      • 1.2 JSON文件的基本结构
      • 1.3 JSON文件的示例
    • 2 Python 解析JSON文件
      • 2.1 解析Json方法
      • 2.2 解析JSON文件实例

    JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。以下是 JSON 文件的完整定义方法和规范。本文还介绍了使用Python处理JSON文件的完整流程,包括读取、解析、修改和保存JSON数据的方法。

    JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。它基于JavaScript编程语言的一个子集,但是独立于语言,许多编程语言都支持JSON。

    JSON文件通常用于存储和传输结构化的数据。一个JSON文件包含一个单独的JSON数据结构,这个结构可以是对象(在Python中对应字典)或数组(在Python中对应列表)。

    {
        "字符串": "Hello, World!",
        "数字": 42,
        "浮点数": 3.14159,
        "布尔值_true": true,
        "布尔值_false": false,
        "空值": null,
        "数组": [1, 2, 3, 4, 5],
        "对象": {
            "键": "值"
        }
    }

    1) 对象(Object)

    用花括号 {} 包围,表示一组无序的键值对。每个键值对中,键是一个字符串,值可以是字符串、数字、布尔值、数组、对象或null。键和值之间用冒号 : 分隔,键值对之间用逗号 , 分隔。

    {
        "基础类型示例": {
            "string": "这是一个字符串",
            "number": 123,
            "float": 45.67,
            "boolean_true": true,
            "boolean_false": false,
            "null_value": null
        },
        "数组示例": [
            "apple",
            "banana",
            "cherry"
        ],
        "嵌套对象示例": {
            "user": {
                "name": "张三",
                "age": 30,
                "email": "zhangsan@example.com"
            }
        }
    }

    2) 数组(Array)

    用方括号 [] 包围,表示一组有序的值。值可以是字符串、数字、布尔值、数组、对象或null。值之间用逗号 , 分隔。

    ["apple", "banana", "cherry"]

    3) 值(Value)

    可以是字符串、数字、布尔值、数组、对象或null。

    JSON数据类型的详细说明:

    • 字符串(String):必须用双引号 " 包围。例如:"Hello"
    • 数字(Number):可以是整数或浮点数,不需要引号。例如:423.14
    • 布尔值(Boolean)true 或 false,不需要引号。
    • 空值(Null)null,表示空值。
    • 对象(Object):如上所述。
    • 数组(Array):如上所述。

    一个典型的JSON文件可能如下所示(例如,一个表示用户信息的JSON文件):

    {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "metadata": {
            "version": "1.0.0",
            "created": "2024-01-01T00:00:00Z",
            "description": "示例 JSON 文件定义",
            "author": "Developer"
        },
        "data": {
            "users": [
                {
                    "id": 1,
                    "username": "alice",
                    "profile": {
                        "firstName": "Alice",
                        "lastName": "Johnson",
                        "age": 28,
                        "email": "alice@example.com",
                        "phone": "+1234567890",
                        "address": {
                            "street": "123 Main St",
                            "city": "New York",
                            "state": "NY",
                            "zipCode": "10001",
                            "country": "USA"
                        }
                    },
                    "preferences": {
                        "theme": "dark",
                        "language": "en-US",
                        "notifications": true,
                        "newsletter": false
                    },
                    "socialMedia": {
                        "twitter": "@alicej",
                        "github": "alicejohnson",
                        "linkedin": "alice-johnson"
                    },
                    "tags": ["developer", "python", "javascript"],
                    "isActive": true,
                    "lastLogin": "2024-01-15T10:30:00Z",
                    "createdAt": "2023-06-01T08:00:00Z"
                },
                {
                    "id": 2,
                    "username": "bob",
                    "profile": {
                        "firstName": "Bob",
                        "lastName": "Smith",
                        "age": 35,
                        "email": "bob@example.com",
                        "phone": "+0987654321",
                        "address": {
                            "street": "456 Oak Ave",
                            "city": "Los Angeles",
                            "state": "CA",
                            "zipCode": "90210",
                            "country": "USA"
                        }
                    },
                    "preferences": {
                        "theme": "light",
                        "language": "en-GB",
                        "notifications": false,
                        "newsletter": true
                    },
                    "socialMedia": {
                        "twitter": "@bobsmith",
                        "github": null,
                        "linkedin": "bob-smith"
                    },
                    "tags": ["designer", "ui/ux", "figma"],
                    "isActive": true,
                    "lastLogin": "2024-01-14T15:45:00Z",
                    "createdAt": "2023-07-15T09:15:00Z"
                }
            ],
            "products": [
                {
                    "id": "P001",
                    "name": "笔记本电脑",
                    "category": "electronics",
                    "price": 999.99,
                    "currency": "USD",
                    "inStock": true,
                    "stockQuantity": 50,
                    "specifications": {
                        "brand": "TechBrand",
                        "model": "X1 Carbon",
                        "processor": "Intel i7",
                        "ram": "16GB",
                        "storage": "512GB SSD",
                        "display": "14英寸"
                    },
                    "features": ["轻薄", "长续航", "高性能"],
                    "images": [
                        "https://example.com/images/product1-1.jpg",
                        "https://example.com/images/product1-2.jpg"
                    ],
                    "reviews": [
                        {
                            "userId": 1,
                            "rating": 5,
                            "comment": "非常棒的笔记本电脑!",
                            "date": "2024-01-10T14:20:00Z"
                        },
                        {
                            "userId": 2,
                            "rating": 4,
                            "comment": "性能不错,但价格稍高",
                            "date": "2024-01-12T09:30:00Z"
                        }
                    ],
                    "tags": ["laptop", "electronics", "portable"],
                    "warranty": {
                        "period": 24,
                        "unit": "months",
                        "type": "manufacturer"
                    }
                }
            ],
            "settings": {
                "pagination": {
                    "pageSize": 20,
                    "maxPageSize": 100
                },
                "cache": {
                    "enabled": true,
                    "ttl": 3600
                },
                "api": {
                    "rateLimit": 1000,
                    "timeout": 30
                }
            }
        },
        "pagination": {
            "totalUsers": 2,
            "totalProducts": 1,
            "currentPage": 1,
            "totalPages": 1,
            "hasNext": false,
            "hasPrevious": false
        }
    }

    在Python中解析JSON文件通常使用内置的json模块。以下是一个简单的步骤:

    1. 导入json模块。
    2. 打开JSON文件。
    3. 使用json.load()函数加载文件内容。

    注意:在打开文件时,我们使用with语句来自动处理文件的关闭。如果JSON文件包含数组,同样可以使用上述方法,返回的将是一个Python列表。另外,如果有一个JSON字符串,可以使用json.loads()函数来解析字符串。

    下面是一个完整的Python程序,演示如何解析JSON文件,并提供多种操作JSON数据的方法。

    该程序实现如下功能:

    1. 读取JSON文件:使用json.load()函数读取JSON文件内容
    2. 显示JSON结构:递归显示JSON数据的层次结构
    3. 提取数据:从JSON中提取特定键的值
    4. 修改数据:向JSON数据中添加新内容
    5. 保存JSON文件:使用json.dump()将数据保存为JSON文件
    6. 错误处理:处理文件不存在、JSON格式错误等异常情况

    1) 源代码文件如下:

    import json
    import os
    from datetime import datetime
    
    def read_json_file(filename):
        """读取JSON文件并返回解析后的数据"""
        try:
            with open(filename, 'r', encoding='utf-8') as file:
                data = json.load(file)
                print(f"成功读取JSON文件: {filename}")
                return data
        except FileNotFoundError:
            print(f"错误: 文件 {filename} 不存在")
            return None
        except json.JSONDecodeError as e:
            print(f"错误: JSON格式不正确 - {e}")
            return None
        except Exception as e:
            print(f"错误: 读取文件时发生错误 - {e}")
            return None
    
    def display_json_structure(data, indent=0):
        """递归显示JSON数据的结构"""
        if isinstance(data, dict):
            for key, value in data.items():
                print("  " * indent + f"├─ {key} ({type(value).__name__})")
                display_json_structure(value, indent + 1)
        elif isinstance(data, list):
            if data:
                print("  " * indent + f"├─ 列表 [{len(data)} 个元素]")
                # 只显示第一个元素的结构作为示例
                if len(data) > 0:
                    display_json_structure(data[0], indent + 1)
            else:
                print("  " * indent + "├─ 空列表")
    
    def extract_values(data, key_to_find):
        """递归查找JSON中特定键的所有值"""
        results = []
        
        if isinstance(data, dict):
            for key, value in data.items():
                if key == key_to_find:
                    results.append(value)
                results.extend(extract_values(value, key_to_find))
        elif isinstance(data, list):
            for item in data:
                results.extend(extract_values(item, key_to_find))
        
        return results
    
    def save_json_file(data, filename):
        """将数据保存为JSON文件"""
        try:
            with open(filename, 'w', encoding='utf-8') as file:
                json.dump(data, file, ensure_ascii=False, indent=2)
            print(f"成功保存JSON文件: {filename}")
        except Exception as e:
            print(f"错误: 保存文件时发生错误 - {e}")
    
    def main():
        # 示例JSON数据
        sample_data = {
            "users": [
                {
                    "id": 1,
                    "name": "张三",
                    "email": "zhangsan@example.com",
                    "age": 28,
                    "is_active": True,
                    "registration_date": "2023-01-15",
                    "hobbies": ["阅读", "游泳", "编程"]
                },
                {
                    "id": 2,
                    "name": "李四",
                    "email": "lisi@example.com",
                    "age": 32,
                    "is_active": False,
                    "registration_date": "2022-11-03",
                    "hobbies": ["摄影", "旅行"]
                },
                {
                    "id": 3,
                    "name": "王五",
                    "email": "wangwu@example.com",
                    "age": 25,
                    "is_active": True,
                    "registration_date": "2023-03-22",
                    "hobbies": ["音乐", "烹饪", "健身", "绘画"]
                }
            ],
            "metadata": {
                "total_users": 3,
                "created": "2023-04-01",
                "version": "1.0"
            }
        }
        
        # 1. 创建示例JSON文件
        filename = "sample_data.json"
        save_json_file(sample_data, filename)
        
        # 2. 读取JSON文件
        data = read_json_file(filename)
        if data is None:
            return
        
        print("n" + "="*50)
        print("JSON文件内容:")
        print("="*50)
        print(json.dumps(data, ensure_ascii=False, indent=2))
        
        # 3. 显示JSON结构
        print("n" + "="*50)
        print("JSON数据结构:")
        print("="*50)
        display_json_structure(data)
        
        # 4. 提取特定信息
        print("n" + "="*50)
        print("提取特定信息:")
        print("="*50)
        
        # 提取所有用户名
        names = extract_values(data, "name")
        print(f"所有用户名: {names}")
        
        # 提取所有邮箱
        emails = extract_values(data, "email")
        print(f"所有邮箱: {emails}")
        
        # 提取活跃用户
        active_users = [user for user in data["users"] if user["is_active"]]
        print(f"活跃用户数量: {len(active_users)}")
        for user in active_users:
            print(f"  - {user['name']} ({user['email']})")
        
        # 5. 修改数据
        print("n" + "="*50)
        print("修改数据:")
        print("="*50)
        
        # 添加新用户
        new_user = {
            "id": 4,
            "name": "赵六",
            "email": "zhaoliu@example.com",
            "age": 29,
            "is_active": True,
            "registration_date": datetime.now().strftime("%Y-%m-%d"),
            "hobbies": ["篮球", "电影"]
        }
        
        data["users"].append(new_user)
        data["metadata"]["total_users"] = len(data["users"])
        data["metadata"]["updated"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        print("添加新用户后:")
        print(f"用户总数: {data['metadata']['total_users']}")
        
        # 6. 保存修改后的数据
        updated_filename = "updated_data.json"
        save_json_file(data, updated_filename)
        
        # 7. 验证保存的文件
        print("n" + "="*50)
        print("验证保存的文件:")
        print("="*50)
        
        updated_data = read_json_file(updated_filename)
        if updated_data:
            print(f"更新后的用户总数: {updated_data['metadata']['total_users']}")
        
        # 8. 清理: 删除创建的文件
        print("n" + "="*50)
        print("清理:")
        print("="*50)
        
        for file_to_remove in [filename, updated_filename]:
            if os.path.exists(file_to_remove):
                os.remove(file_to_remove)
                print(f"已删除文件: {file_to_remove}")
    
    if __name__ == "__main__":
        main()

    2) 运行结果如下:

    成功保存JSON文件: sample_data.json
    成功读取JSON文件: sample_data.json
    
    ==================================================
    JSON文件内容:
    ==================================================
    {
      "users": [
        {
          "id": 1,
          "name": "张三",
          "email": "zhangsan@example.com",
          "age": 28,
          "is_active": true,
          "registration_date": "2023-01-15",
          "hobbies": [
            "阅读",
            "游泳",
            "编程"
          ]
        },
        {
          "id": 2,
          "name": "李四",
          "email": "lisi@example.com",
          "age": 32,
          "is_active": false,
          "registration_date": "2022-11-03",
          "hobbies": [
            "摄影",
            "旅行"
          ]
        },
        {
          "id": 3,
          "name": "王五",
          "email": "wangwu@example.com",
          "age": 25,
          "is_active": true,
          "registration_date": "2023-03-22",
          "hobbies": [
            "音乐",
            "烹饪",
            "健身",
            "绘画"
          ]
        }
      ],
      "metadata": {
        "total_users": 3,
        "created": "2023-04-01",
        "version": "1.0"
      }
    }
    
    ==================================================
    JSON数据结构:
    ==================================================
    ├─ users (list)
      ├─ 列表 [3 个元素]
        ├─ id (int)
        ├─ name (str)
        ├─ email (str)
        ├─ age (int)
        ├─ is_active (bool)
        ├─ registration_date (str)
        ├─ hobbies (list)
          ├─ 列表 [3 个元素]
    ├─ metadata (dict)
      ├─ total_users (int)
      ├─ created (str)
      ├─ version (str)
    
    ==================================================
    提取特定信息:
    ==================================================
    所有用户名: ['张三', '李四', '王五']
    所有邮箱: ['zhangsan@example.com', 'lisi@example.com', 'wangwu@example.com']
    活跃用户数量: 2
      - 张三 (zhangsan@example.com)
      - 王五 (wangwu@example.com)
    
    ==================================================
    修改数据:
    ==================================================
    添加新用户后:
    用户总数: 4
    成功保存JSON文件: updated_data.json
    
    ==================================================
    验证保存的文件:
    ==================================================
    成功读取JSON文件: updated_data.json
    更新后的用户总数: 4
    
    ==================================================
    清理:
    ==================================================
    已删除文件: sample_data.json
    已删除文件: updated_data.json
    
    Process finished with exit code 0

    以上就是Python处理JSON文件的完整流程(读取、解析、修改和保存)的详细内容,更多关于Python处理JSON文件的资料请关注风君子博客其它相关文章!

    您可能感兴趣的文章:

    • Python中的JSON文件处理及遍历方法详解
    • Python中处理JSON文件的超详细指南
    • python实现将JSON文件中的数据格式化处理
    • python处理json文件的四个常用函数
    • 关于python处理大型json文件的方法

    站内搜索