本文目录导读:

纯Python实现(最常用)
简单的格式化函数
import json
def format_json(data):
"""格式化JSON数据"""
try:
# 如果是字符串,先解析
if isinstance(data, str):
parsed = json.loads(data)
else:
parsed = data
# 格式化输出(缩进4个空格)
return json.dumps(parsed, indent=4, ensure_ascii=False)
except json.JSONDecodeError as e:
return f"JSON解析错误: {e}"
# 使用示例
json_string = '{"name":"张三","age":30,"city":"北京"}'
formatted = format_json(json_string)
print(formatted)
带排序和中文处理的增强版
import json
from datetime import datetime
def format_json_advanced(data, sort_keys=False, indent=4):
"""高级JSON格式化"""
try:
if isinstance(data, str):
parsed = json.loads(data)
else:
parsed = data
return json.dumps(
parsed,
indent=indent,
sort_keys=sort_keys,
ensure_ascii=False, # 支持中文
separators=(',', ': ') # 美化分隔符
)
except Exception as e:
return f"格式化失败: {e}"
命令行脚本(Python)
创建 json_formatter.py:
#!/usr/bin/env python3
import sys
import json
def main():
if len(sys.argv) < 2:
print("用法: python json_formatter.py <输入文件> [输出文件]")
print("或: echo '{\"key\":\"value\"}' | python json_formatter.py")
sys.exit(1)
# 从文件或标准输入读取
if sys.argv[1] == '-':
data = sys.stdin.read()
else:
with open(sys.argv[1], 'r', encoding='utf-8') as f:
data = f.read()
try:
parsed = json.loads(data)
formatted = json.dumps(parsed, indent=4, ensure_ascii=False)
# 输出到文件或标准输出
if len(sys.argv) >= 3 and sys.argv[2] != '-':
with open(sys.argv[2], 'w', encoding='utf-8') as f:
f.write(formatted)
print(f"已保存到 {sys.argv[2]}")
else:
print(formatted)
except json.JSONDecodeError as e:
print(f"JSON解析错误: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
利用内置 json.tool 模块
Python自带JSON工具,无需安装:
# 格式化文件
python -m json.tool input.json > formatted.json
# 管道输入
echo '{"name":"张三","age":30}' | python -m json.tool
# 保持中文
echo '{"name":"张三"}' | python -c "import sys,json; json.dump(json.load(sys.stdin), sys.stdout, indent=2, ensure_ascii=False)"
浏览器中的JavaScript实现
// 简单的格式化函数
function formatJSON(json) {
try {
// 如果是字符串,先解析
const obj = typeof json === 'string' ? JSON.parse(json) : json;
// 格式化输出
return JSON.stringify(obj, null, 2);
} catch (error) {
return `JSON格式错误: ${error.message}`;
}
}
// 带更多选项的版本
function formatJSONAdvanced(json, options = {}) {
const {
indent = 2,
sortKeys = false,
maxLength = 80
} = options;
try {
const obj = typeof json === 'string' ? JSON.parse(json) : json;
return JSON.stringify(obj, (key, value) => {
// 自定义替换逻辑
return value;
}, indent);
} catch (error) {
return `JSON格式错误: ${error.message}`;
}
}
// 使用示例
const messyJson = '{"name":"Alice","age":30,"hobbies":["reading","coding"]}';
console.log(formatJSON(messyJson));
完整的命令行工具(Python)
创建 json_tool.py 支持更多功能:
#!/usr/bin/env python3
import json
import sys
import os
def format_data(data, options):
"""格式化JSON数据"""
try:
parsed = json.loads(data)
except json.JSONDecodeError:
# 尝试修复常见错误
data = data.strip()
if data.startswith("'") and data.endswith("'"):
data = data[1:-1]
try:
parsed = json.loads(data)
except:
raise ValueError("无法解析JSON")
return json.dumps(
parsed,
indent=options.get('indent', 2),
sort_keys=options.get('sort', False),
ensure_ascii=not options.get('chinese', True),
check_circular=options.get('check', True)
)
def main():
import argparse
parser = argparse.ArgumentParser(description='JSON格式化工具')
parser.add_argument('input', nargs='?', help='输入文件')
parser.add_argument('-o', '--output', help='输出文件')
parser.add_argument('-i', '--indent', type=int, default=2, help='缩进空格数')
parser.add_argument('-s', '--sort', action='store_true', help='按键排序')
parser.add_argument('--no-chinese', action='store_true', help='转义中文字符')
args = parser.parse_args()
# 读取数据
if args.input:
with open(args.input, 'r', encoding='utf-8') as f:
data = f.read()
else:
data = sys.stdin.read()
# 格式化
options = {
'indent': args.indent,
'sort': args.sort,
'chinese': not args.no_chinese
}
try:
result = format_data(data, options)
if args.output:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(result)
print(f"已保存到 {args.output}")
else:
print(result)
except Exception as e:
print(f"错误: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
在线格式化的完整HTML页面
<!DOCTYPE html>
<html>
<head>JSON格式化工具</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
textarea { width: 100%; height: 200px; font-family: monospace; }
button { padding: 10px 20px; margin: 10px 0; }
#result { background: #f5f5f5; padding: 10px; border-radius: 5px; }
.error { color: red; }
</style>
</head>
<body>
<h1>JSON格式化工具</h1>
<textarea id="input" placeholder="粘贴JSON数据..."></textarea>
<div>
<button onclick="format()">格式化</button>
<button onclick="compress()">压缩</button>
<button onclick="validate()">验证</button>
</div>
<textarea id="output" placeholder="结果..." readonly></textarea>
<script>
function format() {
try {
const input = document.getElementById('input').value;
const parsed = JSON.parse(input);
document.getElementById('output').value =
JSON.stringify(parsed, null, 2);
} catch (e) {
document.getElementById('output').value =
`错误: ${e.message}`;
}
}
function compress() {
try {
const input = document.getElementById('input').value;
const parsed = JSON.parse(input);
document.getElementById('output').value =
JSON.stringify(parsed);
} catch (e) {
document.getElementById('output').value =
`错误: ${e.message}`;
}
}
function validate() {
try {
JSON.parse(document.getElementById('input').value);
alert('有效的JSON格式!');
} catch (e) {
alert(`无效的JSON: ${e.message}`);
}
}
</script>
</body>
</html>
使用建议
- 简单使用:直接用
python -m json.tool - 开发集成:使用Python的
json模块 - Web应用:使用浏览器的
JSON.stringify() - 命令行工具:用argparse创建完整工具
- 大型文件:支持流式读取和写入
选择哪种方法取决于你的具体需求和使用场景。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播