Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python json文件处理

作者:▍看女人酒醒的疯癫。   发布日期:2026-05-26   浏览:93

# Python处理JSON文件的示例代码

import json

# 读取JSON文件
def read_json(file_path):
    """
    读取JSON文件并返回解析后的Python对象。

    参数:
    file_path (str): JSON文件的路径

    返回:
    dict or list: 解析后的Python对象(通常是字典或列表)
    """
    with open(file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
    return data

# 写入JSON文件
def write_json(file_path, data):
    """
    将Python对象写入JSON文件。

    参数:
    file_path (str): 要写入的JSON文件路径
    data (dict or list): 要写入的Python对象(通常是字典或列表)
    """
    with open(file_path, 'w', encoding='utf-8') as file:
        json.dump(data, file, ensure_ascii=False, indent=4)

# 示例用法
if __name__ == "__main__":
    # 示例数据
    example_data = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }

    # 写入JSON文件
    write_json('example.json', example_data)

    # 读取JSON文件
    loaded_data = read_json('example.json')
    print(loaded_data)

解释说明:

  1. 导入模块:使用 json 模块来处理JSON数据。
  2. 读取JSON文件:定义 read_json 函数,接受文件路径作为参数,读取并解析JSON文件,返回Python对象(通常是字典或列表)。
  3. 写入JSON文件:定义 write_json 函数,接受文件路径和要写入的数据作为参数,将Python对象写入JSON文件。
  4. 示例用法:在 __main__ 中创建一个示例数据字典,调用 write_json 将其写入文件,再调用 read_json 读取并打印内容。

这样可以方便地处理JSON文件的读写操作。

上一篇:python中count函数的用法

下一篇:python与人工智能

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python的assert基本用法

python开发windows应用程序

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站