🛠️ToolsShed

JSON Formatter & Validator

格式化、验证和美化 JSON 数据。

Formatted JSON will appear here...

JSON Formatter 是一款免费的浏览器工具,可即时美化或压缩 JSON 数据。它解析原始 JSON 字符串,检查语法错误,并应用适当的缩进和语法高亮,使即使是深度嵌套的结构也易于阅读。

将 JSON 粘贴到输入框中,点击「格式化」可获得带缩进的输出,点击「压缩」可将其压缩成一行以用于生产环境。验证器会精确指出语法错误的位置,方便快速修正。

该工具完全在浏览器中运行,不会将任何数据发送到服务器。非常适合调试 API 响应、编辑配置文件以及在发送给服务之前准备 JSON 有效负载。

常见问题

代码实现

import json

# Format (pretty-print) a JSON string
raw = '{"name":"Alice","age":30,"hobbies":["reading","coding"]}'
data = json.loads(raw)

# Indent with 2 spaces
pretty = json.dumps(data, indent=2)
print(pretty)
# {
#   "name": "Alice",
#   "age": 30,
#   "hobbies": ["reading", "coding"]
# }

# Sort keys alphabetically
sorted_json = json.dumps(data, indent=2, sort_keys=True)

# Minify (compact)
minified = json.dumps(data, separators=(',', ':'))
print(minified)
# {"name":"Alice","age":30,"hobbies":["reading","coding"]}

# Format a JSON file in-place
with open('data.json', 'r') as f:
    obj = json.load(f)
with open('data.json', 'w') as f:
    json.dump(obj, f, indent=2)

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.