import json # 示例JSON数据 data = { "name": "Alice", "age": 30, "city": "New York", "is_student": False, "courses": ["Math", "Science", "Art"] } # 打印格式化的JSON数据 formatted_json = json.dumps(data, indent=4) print(formatted_json) 运行这段代码后,你会得到如下格式的JS...
# 将Python对象格式化输出为JSON字符串formatted_data = json.dumps(data, indent=4, sort_keys=True)# 写入文件或直接打印输出with open('formatted_data.json', 'w') as file: file.write(formatted_data)print(formatted_data)上述代码中,indent参数用于设定缩进的空格数,sort_keys参数用于对输出的JSON对...
data={"name":"Alice","age":25,"city":"New York"}formatted_json=json.dumps(data,indent=4)print(formatted_json) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 上面的代码中,我们先定义了一个包含个人信息的 JSON 数据data,然后使用json.dumps()方法将其格式化为字符串,并设置了indent=4参数,表示缩进...
在上面的示例中,我们使用print()函数输出了解析后的JSON数据。然而,输出的数据并没有进行格式化,很难阅读。为了让输出的JSON数据更易于阅读,我们可以使用json.dumps()方法,并设置indent参数来实现格式化输出。 # 格式化输出JSON数据formatted_json=json.dumps(json_data,indent=4)# 打印格式化输出print(formatted_json)...
print(formatted_data) ``` 3.写入格式化后的数据到新文件 如果需要将格式化后的数据写入到新的JSON文件中,可以使用`json.dump()`函数来实现。 ```python #写入格式化后的数据到新文件 with open('formatted_data.json','w')as file: json.dump(data,file,indent=4) ...
print(formatted_data) ``` 3.写入格式化后的数据到新文件 如果需要将格式化后的数据写入到新的JSON文件中,可以使用`json.dump()`函数来实现。 ```python #写入格式化后的数据到新文件 with open('formatted_data.json','w')as file: json.dump(data,file,indent=4) ...
print(formatted_json) # 按照键进行排序输出JSON sorted_json = json.dumps(data, sort_keys=True) print(sorted_json) 输出结果: 代码语言:txt 复制 {"name": "John", "age": 30, "city": "New York"} { "name": "John", "age": 30, ...
json.dumps方法源码: defdumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw): """Serialize ``obj`` to a JSON formatted ``str``. ...
data = json.load(result) print(type(data)) # <class 'list'> 三. json.dumps() 官方解释: """Serialize ``obj`` to a JSON formatted ``str``. 将python对象转换为json对象,可以理解为将字典转换为字符串,例如: s = {"name":"mqy","age":"23"} ...
数据data={"name":"Alice","age":30,"city":"New York","skills":["Python","Django","Machine Learning"]}# 格式化 JSON 数据formatted_json=json.dumps(data,indent=4)# 将 JSON 数据格式化为更易读的形式,缩进为 4 个空格# 打印格式化后的 JSON 数据print(formatted_json)# 输出格式化后的 JSON ...