Python中实现JSON数据读写的编程实战指南

文章目录
  • JSON 全称是 JavaScript Object Notation,即 JavaScript 对象表示法,它是一种轻量级的数据交换格式,具有以下特点 使用键值对存储数据 类似于 Python 的字典 结构清晰 可嵌套 支持多种基本数据类型 语言无关 可跨平台 一个典型的 JSON 示例 { “name”: “Alice”, “age”: 25, “is_student”: false, “skills”: [“Python”, “Java”, “SQL”] } 在 Python 中 这种结构与字典类型非常相似 因此二者可以轻松互转
  • JSON 类型 Python 类型 object dict array list string str number int 或 float true True false False null None 这种对应关系让 JSON 数据与 Python 数据结构之间的转换非常自然
  • Python 内置的 json 模块提供了四个核心方法 方法 作用 json.dumps() 将 Python 对象转换为 JSON 字符串 json.loads() 将 JSON 字符串解析为 Python 对象 json.dump() 将 Python 对象写入 JSON 文件 json.load() 从 JSON 文件读取并转换为 Python 对象
  • import json data = { “name”: “Alice”, “age”: 25, “skills”: [“Python”, “Data Analysis”] } json_str = json.dumps(data, ensure_ascii=False, indent=4) print(json_str) 输出结果 {    "name": "Alice",    "age": 25,    "skills": [        "Python",        "Data Analysis"    ]} 参数说明 ensure_ascii=False:防止中文被转义 indent=4:设置缩进格式 让输出更易读
  • import json json_str = ‘{“name”: “Alice”, “age”: 25, “skills”: [“Python”, “Data Analysis”]}’ data = json.loads(json_str) print(data[“name”]) 输出 Alice
  • 将数据保存到文件非常常见 例如保存配置或用户信息 import json user = { “id”: 1001, “name”: “Bob”, “vip”: True, “balance”: 99.8 } with open(“user.json”, “w”, encoding=”utf-8″) as f: json.dump(user, f, ensure_ascii=False, indent=4) print(“JSON 文件写入完成”) 执行后 你将在当前目录生成一个名为 user.json 的文件
  • import json with open(“user.json”, “r”, encoding=”utf-8″) as f: user_info = json.load(f) print(user_info) print(type(user_info)) 输出 {'id': 1001, 'name': 'Bob', 'vip': True, 'balance': 99.8}<class 'dict'> 说明从文件中读取的 JSON 已成功转换为 Python 字典对象
  • 假设我们有一个配置文件 config.json { “version”: “1.0”, “debug”: true, “users”: [“admin”, “guest”] } 我们想读取其中内容 并更新某些字段 import json # 读取配置 with open(“config.json”, “r”, encoding=”utf-8″) as f: config = json.load(f) # 修改参数 config[“debug”] = False config[“users”].append(“developer”) # 保存回文件 with open(“config.json”, “w”, encoding=”utf-8″) as f: json.dump(config, f, ensure_ascii=False, indent=4) print(“配置文件已更新”)
  • 在处理 JSON 文件时 可能会遇到文件缺失或格式错误 可以使用 try…except 捕获异常 import json try: with open(“data.json”, “r”, encoding=”utf-8″) as f: data = json.load(f) except FileNotFoundError: print(“文件未找到”) except json.JSONDecodeError: print(“JSON 格式错误”) else: print(“读取成功”)
  • JSON 是 Python 与外部世界交互的桥梁 无论是 API 通信 还是数据存储 JSON 都是最常见也最重要的数据格式之一 学习要点 使用 json.dumps() 与 json.loads() 实现内存中数据的转换 使用 json.dump() 与 json.load() 操作文件 养成使用 with open() 的好习惯 处理异常 提高代码健壮性 掌握 JSON 数据读写后 你已经具备处理各种接口数据与配置文件的能力 这将在实际项目中为你带来巨大的便利 到此这篇关于Python中实现JSON数据读写的编程实战指南的文章就介绍到这了,更多相关Python JSON数据读写内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: python读写json、格式化写入json文件实现方式 全方位解析Python读写JSON数据的实战指南 Python Json读写操作之JsonPath用法详解 Python如何读写JSON格式数据 Python读写JSON文件的操作详解 详解python读写json文件 Python实现的读写json文件功能示例
  • 目录
    • 一 什么是 JSON
    • 二 JSON 与 Python 数据类型对应关系
    • 三 Python JSON 模块常用方法
    • 四 Python 对象转 JSON 字符串
    • 五 JSON 字符串转 Python 对象
    • 六 写入 JSON 文件
    • 七 从文件中读取 JSON 数据
    • 八 实战 案例 读取配置文件并修改
    • 九 异常处理与健壮性
    • 十 小结

    在现代编程中 数据交换是不可或缺的一部分,无论是 Web 开发、接口通信、还是配置文件存储 JSON 格式都是应用最广泛的数据格式之一,Python 对 JSON 的支持非常完善,通过内置模块 json 就能轻松实现数据的序列化与反序列化。

    本文将带你深入理解 JSON 的概念以及在 Python 中的读写操作方法

    JSON 全称是 JavaScript Object Notation,即 JavaScript 对象表示法,它是一种轻量级的数据交换格式,具有以下特点

    • 使用键值对存储数据 类似于 Python 的字典
    • 结构清晰 可嵌套
    • 支持多种基本数据类型
    • 语言无关 可跨平台

    一个典型的 JSON 示例

    {
      "name": "Alice",
      "age": 25,
      "is_student": false,
      "skills": ["Python", "Java", "SQL"]
    }
    

    在 Python 中 这种结构与字典类型非常相似 因此二者可以轻松互转

    JSON 类型 Python 类型
    object dict
    array list
    string str
    number int 或 float
    true True
    false False
    null None

    这种对应关系让 JSON 数据与 Python 数据结构之间的转换非常自然

    Python 内置的 json 模块提供了四个核心方法

    方法 作用
    json.dumps() 将 Python 对象转换为 JSON 字符串
    json.loads() 将 JSON 字符串解析为 Python 对象
    json.dump() 将 Python 对象写入 JSON 文件
    json.load() 从 JSON 文件读取并转换为 Python 对象

    import json
    
    data = {
        "name": "Alice",
        "age": 25,
        "skills": ["Python", "Data Analysis"]
    }
    
    json_str = json.dumps(data, ensure_ascii=False, indent=4)
    print(json_str)
    

    输出结果

    {
        "name": "Alice",
        "age": 25,
        "skills": [
            "Python",
            "Data Analysis"
        ]
    }

    参数说明

    • ensure_ascii=False:防止中文被转义
    • indent=4:设置缩进格式 让输出更易读

    import json
    
    json_str = '{"name": "Alice", "age": 25, "skills": ["Python", "Data Analysis"]}'
    data = json.loads(json_str)
    print(data["name"])
    

    输出

    Alice

    将数据保存到文件非常常见 例如保存配置或用户信息

    import json
    
    user = {
        "id": 1001,
        "name": "Bob",
        "vip": True,
        "balance": 99.8
    }
    
    with open("user.json", "w", encoding="utf-8") as f:
        json.dump(user, f, ensure_ascii=False, indent=4)
    
    print("JSON 文件写入完成")
    

    执行后 你将在当前目录生成一个名为 user.json 的文件

    import json
    
    with open("user.json", "r", encoding="utf-8") as f:
        user_info = json.load(f)
    
    print(user_info)
    print(type(user_info))
    

    输出

    {'id': 1001, 'name': 'Bob', 'vip': True, 'balance': 99.8}
    <class 'dict'>

    说明从文件中读取的 JSON 已成功转换为 Python 字典对象

    假设我们有一个配置文件 config.json

    {
      "version": "1.0",
      "debug": true,
      "users": ["admin", "guest"]
    }
    

    我们想读取其中内容 并更新某些字段

    import json
    
    # 读取配置
    with open("config.json", "r", encoding="utf-8") as f:
        config = json.load(f)
    
    # 修改参数
    config["debug"] = False
    config["users"].append("developer")
    
    # 保存回文件
    with open("config.json", "w", encoding="utf-8") as f:
        json.dump(config, f, ensure_ascii=False, indent=4)
    
    print("配置文件已更新")
    

    在处理 JSON 文件时 可能会遇到文件缺失或格式错误 可以使用 try...except 捕获异常

    import json
    
    try:
        with open("data.json", "r", encoding="utf-8") as f:
            data = json.load(f)
    except FileNotFoundError:
        print("文件未找到")
    except json.JSONDecodeError:
        print("JSON 格式错误")
    else:
        print("读取成功")
    

    JSON 是 Python 与外部世界交互的桥梁 无论是 API 通信 还是数据存储 JSON 都是最常见也最重要的数据格式之一

    学习要点

    • 使用 json.dumps()json.loads() 实现内存中数据的转换
    • 使用 json.dump()json.load() 操作文件
    • 养成使用 with open() 的好习惯
    • 处理异常 提高代码健壮性

    掌握 JSON 数据读写后 你已经具备处理各种接口数据与配置文件的能力 这将在实际项目中为你带来巨大的便利

    到此这篇关于Python中实现JSON数据读写的编程实战指南的文章就介绍到这了,更多相关Python JSON数据读写内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

    您可能感兴趣的文章:

    • python读写json、格式化写入json文件实现方式
    • 全方位解析Python读写JSON数据的实战指南
    • Python Json读写操作之JsonPath用法详解
    • Python如何读写JSON格式数据
    • Python读写JSON文件的操作详解
    • 详解python读写json文件
    • Python实现的读写json文件功能示例

    站内搜索