酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

写一段python格式化json字符串算法

这是一个简单的Python函数,它将一个Python字典转换为格式化的JSON字符串: ```python import json def format_json(json_str): return json.dumps(json.loads(json_str), indent=4, sort_keys=True) ``` 这个函数首先使用`json.loads()`函数将JSON字符串转换回Python字典,然后使用`json.dumps()`函数将字典转换回JSON字符串。`indent=4`参数用于设置缩进,`sort_keys=True`参数用于按字母顺序排序键。 例如: ```python json_str = '{"name": "John", "age": 30, "city": "New York"}' print(format_json(json_str)) ``` 输出: ```json { "age": 30, "city": "New York", "name": "John" } ``` [2023-10-25 20:51:52 | AI写代码神器 | 486点数解答]

相关提问