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

python json数据处理

作者:战神再世   发布日期:2025-03-13   浏览:150

import json

# 示例JSON字符串
json_string = '{"name": "Alice", "age": 25, "city": "New York"}'

# 将JSON字符串解析为Python字典
parsed_data = json.loads(json_string)
print("解析后的Python字典:", parsed_data)

# 修改字典中的数据
parsed_data['age'] = 26

# 将Python字典转换回JSON字符串
new_json_string = json.dumps(parsed_data)
print("转换后的JSON字符串:", new_json_string)

# 写入JSON数据到文件
with open('data.json', 'w') as json_file:
    json.dump(parsed_data, json_file)

# 从文件读取JSON数据
with open('data.json', 'r') as json_file:
    data_from_file = json.load(json_file)
    print("从文件读取的JSON数据:", data_from_file)

解释说明:

  1. 导入模块:使用 import json 导入Python的内置JSON处理模块。
  2. 解析JSON字符串:使用 json.loads() 方法将JSON格式的字符串解析为Python字典。
  3. 修改字典数据:直接对解析后的字典进行修改。
  4. 转换回JSON字符串:使用 json.dumps() 方法将Python字典转换回JSON格式的字符串。
  5. 写入JSON文件:使用 json.dump() 方法将Python字典写入JSON文件。
  6. 读取JSON文件:使用 json.load() 方法从JSON文件中读取数据并解析为Python字典。

通过这些步骤,你可以轻松地在Python中处理JSON数据。

上一篇:python 遍历dict

下一篇:python语言程序设计基础

大家都在看

python时间格式

python ord和chr

python中的yield

python自定义异常

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

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

Laravel 中文站