json.dumps()及indent参数

json.dumps() 使字典类型漂亮的输出
indent参数决定添加几个空格

cla_dict = {“0”: “daisy”, “1”: “dandelion”, “2”: “roses”, “3”: “sunflowers”, “4”: “tulips”}
cla_dict
{‘0’: ‘daisy’, ‘1’: ‘dandelion’, ‘2’: ‘roses’, ‘3’: ‘sunflowers’, ‘4’: ‘tulips’}

import json
print(json.dumps(cla_dict))
{“0”: “daisy”, “1”: “dandelion”, “2”: “roses”, “3”: “sunflowers”, “4”: “tulips”}

print(json.dumps(cla_dict, indent=4))
{
“0”: “daisy”,
“1”: “dandelion”,
“2”: “roses”,
“3”: “sunflowers”,
“4”: “tulips”
}

print(json.dumps(cla_dict, indent=20))
{
“0”: “daisy”,
“1”: “dandelion”,
“2”: “roses”,
“3”: “sunflowers”,
“4”: “tulips”
}

`json.dumps` 是 Python 中 `json` 模块的一个函数,用于将 Python 对象编码为 JSON 格式的字符串。它可以将 Python 的字典、列表、元组等数据结构转换为 JSON 格式的字符串,方便数据的存储和传输。 以下是 `json.dumps` 的一些常见用法: 1. **基本用法**: ```python import json data = {'name': 'John', 'age': 30, 'city': 'New York'} json_str = json.dumps(data) print(json_str) ``` 输出: ``` {"name": "John", "age": 30, "city": "New York"} ``` 2. **指定参数**: `json.dumps` 还可以接受一些参数来控制输出的格式,例如 `indent` 参数可以美化输出,`ensure_ascii` 参数可以控制是否对非 ASCII 字符进行转义。 ```python import json data = {'name': '张三', 'age': 30, 'city': '北京'} json_str = json.dumps(data, indent=4, ensure_ascii=False) print(json_str) ``` 输出: ``` { "name": "张三", "age": 30, "city": "北京" } ``` 3. **处理复杂数据结构**: `json.dumps` 可以处理嵌套的复杂数据结构。 ```python import json data = { 'name': 'John', 'age': 30, 'city': 'New York', 'skills': ['Python', 'Java', 'C++'], 'education': { 'undergraduate': 'B.Sc. Computer Science', 'graduate': 'M.Sc. Data Science' } } json_str = json.dumps(data, indent=4) print(json_str) ``` 输出: ```json { "name": "John", "age": 30, "city": "New York", "skills": [ "Python", "Java", "C++" ], "education": { "undergraduate": "B.Sc. Computer Science", "graduate": "M.Sc. Data Science" } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值