Replace thedatadictionary with your actual JSON data. Theindent=4argument injson.dumps()specifies the number of spaces for indentation (you can adjust it as needed). When you run this code, it will print the JSO
importjson# 导入 JSON 模块# 创建一个字典data={"name":"Alice",# 设置键值对"age":30,"city":"Wonderland","hobbies":["reading","gardening","coding"]}# 将字典转换为带缩进的 JSON 字符串json_string=json.dumps(data,indent=4)# 输出带缩进的 JSON 字符串print(json_string) 1. 2. 3. 4. ...
>>> print(json.dumps({ 4 : 5, 6 : 7}, sort_keys=True, indent=4)) # python中的键是字符串,用单引号 # 结果显示 { "4": 5, # 变成双引号 "6": 7 } 1. 2. 3. 4. 5. 6. 7. 8. 2、对json数据通过缩进符美观输出,使用indent参数 information4 = { name : 小明 , age : 18,...
json.dumps() :是对数据进行编码 #coding=gbk import json dicts={"name":"lucy","sex":"boy"} json_dicts=json.dumps(dicts) print(json_dicts) 输出的结果是: 这样的格式一般都不优美,当数据很多的时候,看得就不是很直观方便,现在用一个参数来对json进行数据格式化输出 使用indent=4 这个参数 用法如下:...
print(json_string) # 输出:{"name": "John Doe", "age": 30, "is_student": false, "hobbies": ["reading", "hiking", "swimming"]} 格式化输出JSON 在上面的示例中,生成的JSON字符串是紧凑的,没有换行或缩进。如果您希望以更可读的方式输出JSON,可以使用indent参数来进行格式化输出。indent参数指定了...
print(formatted_data) ``` 3.写入格式化后的数据到新文件 如果需要将格式化后的数据写入到新的JSON文件中,可以使用`json.dump()`函数来实现。 ```python #写入格式化后的数据到新文件 with open('formatted_data.json','w')as file: json.dump(data,file,indent=4) ...
import jsond = {'id':'001', 'name':'张三', 'age':'20'}j = json.dumps(d, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ': '))print(j)执行结果:{ "age": "20", "id": "001", "name": "张三"} 当然,除了字典类型外,其他一些 Python 类型也可转...
importjson# 定义一个Python字典data={"name":"Alice","age":25,"city":"London"}# 将数据写入JSON文件withopen("data.json","w")asfile:json.dump(data,file,indent=2)# 从JSON文件中读取数据withopen("data.json","r")asfile:loaded_data=json.load(file)# 打印加载后的数据print(loaded_data) ...
(letters)}]), 'layer3_2': 'string', 'layer3_3': NoIndent([{"x":2,"y":8,"z":3}, {"x":1,"y":5,"z":4}, {"x":6,"y":9,"z":8}]), 'layer3_4': NoIndent(list(range(20))), } } } print(json.dumps(data_structure, cls=MyEncoder, sort_keys=True, indent=2))...
obj2)>>> json_str2=json.dumps(python_obj2,sort_keys=True,indent=2)>>> print json_str2{ "key1": [ >> python_obj2={"key2": [4, 5, 6], "key1": [1, 2, 3]}>>> json_str2=json.dumps(python_obj2)>>> json_str2=json.dumps(python_obj2,sort_keys=True,indent=2)>...