python读写JSON(JavaScript Object Notation)编码格式的数据

这篇博客介绍了如何在Python中进行JSON数据的编码和解码。使用`dumps`函数可以将变量编码为JSON格式,同时讨论了`ensure_ascii`、`indent`和`sort_keys`参数的影响。另一方面,通过文件读取和导入,展示了如何处理JSON格式的文件。
部署运行你感兴趣的模型镜像

JSON(JavaScript Object Notation)编码格式的数据。

  • 1、变量解码、编码为Json格式

  • 2、文件读出、导入json格式

使用json时需要注意的地方:python中字典的key在经过json转化后都变成了string类型

1、变量解码、编码为Json格式

dumps函数

json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
  • ensure_ascii:比较关键,True代表显示为编码形式,这个一般在中文里面特别不好用,所以建议关掉。
  • ndent:代表缩进,
  • sort_keys:代表会否按照某些顺序排列

编码

import json

#dict
data = {
	'name' : 'ACME',
    'shares' : 100,
    'price' : 542.23
}

json_str = json.dumps(data)  # 编码
json_str

结果输出

'{"price": 542.23, "shares": 100, "name": "ACME"}'

解码

data = json.loads(json_str)  # 解码
data

结果输出

{'name': 'ACME', 'price': 542.23, 'shares': 100}

2、文件读出、导入json格式

# Writing JSON data
with open('data.json', 'w') as f:
    json.dump(data, f)

# Reading data back
with open('data.json', 'r') as f:
    data = json.load(f)

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

<think> We are given a user question about reading and writing JSON in Python, and we have several references that cover this topic. The references provide information on: - Using `json.loads()` to convert a JSON string to a Python object [^1] - Using `json.dump()` to write a Python object to a JSON file and `json.load()` to read from a JSON file [^1][^2] - The distinction between `dump`/`dumps` and `load`/`loads` [^3] - A brief introduction to JSON [^4] The user's question is: "我想查找Python读写JSON的方法 请问Python读写JSON的实现方法" We'll structure the answer as follows: 1. Introduction to JSON and Python's json module. 2. Converting JSON string to Python object (using `json.loads()`). 3. Converting Python object to JSON string (using `json.dumps()`). 4. Writing JSON to a file (using `json.dump()`). 5. Reading JSON from a file (using `json.load()`). We'll also include code examples for each operation. Since the references are consistent, we can safely use them to build the answer. Note: The references are: [^1]: Example of `json.loads()`, `json.dump()`, and `json.load()`. [^2]: Example of reading a JSON file with `json.load()`. [^3]: Summary of the functions. [^4]: Brief about JSON. We'll generate a clear step-by-step guide. </think> ### Python读写JSON的实现方法 JSONJavaScript Object Notation)是一种轻量级数据交换格式Python通过内置`json`模块提供完整的JSON处理支持[^4]。以下是具体实现方法: --- #### 1. **JSON字符串 ↔ Python对象** ```python import json # Python对象 → JSON字符串 data = {"name": "张三", "age": 25, "courses": ["数学", "物理"]} json_str = json.dumps(data, ensure_ascii=False) # 中文需关闭ASCII转义 print(f"JSON字符串: {json_str}") # 输出: {"name": "张三", "age": 25, "courses": ["数学", "物理"]} # JSON字符串 → Python对象 python_obj = json.loads(json_str) print(f"Python对象类型: {type(python_obj)}") # 输出: <class 'dict'> ``` --- #### 2. **JSON文件读写** ```python # 写入JSON文件 with open("data.json", "w", encoding="utf-8") as f: json.dump(data, f, indent=4, ensure_ascii=False) # indent控制缩进 # 读取JSON文件 with open("data.json", "r", encoding="utf-8") as f: loaded_data = json.load(f) print(f"文件内容: {loaded_data}") ``` --- #### 3. **数据类型映射关系 | **JSON类型** | **Python类型** | 示例 | |--------------|------------------|--------------------------| | object | `dict` | `{"key": "value"}` | | array | `list` | `[1, 2, 3]` | | string | `str` | `"text"` | | number | `int`/`float` | `42` 或 `3.14` | | true/false | `bool` | `True`/`False` | | null | `None` | `None` | > 特殊场景处理: > - 日期对象:需自定义序列化函数 > ```python > from datetime import datetime > def date_handler(obj): > if isinstance(obj, datetime): > return obj.isoformat() > ``` > - 非ASCII字符:使用`ensure_ascii=False`参数 --- #### 4. **高级功能** - **美化输出**:`json.dumps(data, indent=4)` - **自定义序列化**: ```python class User: def __init__(self, name): self.name = name def custom_encoder(obj): if isinstance(obj, User): return {"name": obj.name} user = User("李四") print(json.dumps(user, default=custom_encoder)) # 输出: {"name": "李四"} ``` --- ### 关键方法对比 | **方法** | 作用 | 输入/输出类型 | |---------------|-------------------------------|---------------------| | `json.dumps()` | Python对象 → JSON字符串 | 返回`str` | | `json.loads()` | JSON字符串 → Python对象 | 返回`dict`/`list` | | `json.dump()` | Python对象 → JSON文件 | 直接写入文件 | | `json.load()` | JSON文件 → Python对象 | 返回`dict`/`list` | > **注意事项**: > 1. 文件操作需指定编码(如`encoding='utf-8'`) > 2. 自定义对象需实现序列化逻辑 > 3. 大文件处理建议逐行读取解析 JSON作为现代Web应用的标准数据格式Python的`json`模块提供了简洁高效的解决方案[^1][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值