本文目录导读:

我来介绍几种实现接口数据格式化的脚本方法。
Python脚本实现
基础格式化脚本
import json
import requests
from typing import Any, Dict, List
def format_api_response(response_data: Any, indent: int = 2) -> str:
"""
格式化API响应数据
"""
if isinstance(response_data, str):
try:
# 尝试解析JSON字符串
data = json.loads(response_data)
return json.dumps(data, indent=indent, ensure_ascii=False)
except json.JSONDecodeError:
return response_data
else:
return json.dumps(response_data, indent=indent, ensure_ascii=False)
# 示例用法
api_response = '{"name": "张三", "age": 25, "hobbies": ["读书", "游泳"]}'
formatted = format_api_response(api_response)
print(formatted)
高级格式化工具
import json
import requests
from typing import Optional, Dict, Any
class ApiFormatter:
def __init__(self, base_url: str = None):
self.base_url = base_url
self.session = requests.Session()
def fetch_and_format(self, url: str, method: str = 'GET',
params: Dict = None, headers: Dict = None) -> str:
"""
获取API数据并格式化
"""
if self.base_url:
url = f"{self.base_url}{url}"
try:
response = self.session.request(method, url,
params=params,
headers=headers)
response.raise_for_status()
# 尝试解析JSON
try:
data = response.json()
return self._pretty_format(data)
except:
# 如果不是JSON,返回原始文本
return response.text
except requests.exceptions.RequestException as e:
return f"请求错误: {str(e)}"
def _pretty_format(self, data: Any, indent: int = 2) -> str:
"""
漂亮格式化JSON数据
"""
return json.dumps(data, indent=indent, ensure_ascii=False,
sort_keys=True)
def format_from_file(self, file_path: str) -> str:
"""
从文件读取并格式化JSON
"""
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
return self._pretty_format(data)
def save_formatted(self, data: Any, output_path: str):
"""
保存格式化后的数据到文件
"""
formatted = self._pretty_format(data)
with open(output_path, 'w', encoding='utf-8') as f:
f.write(formatted)
# 使用示例
formatter = ApiFormatter()
result = formatter.fetch_and_format('https://api.example.com/data')
print(result)
JavaScript/Node.js脚本
const axios = require('axios');
class ApiFormatter {
constructor(config = {}) {
this.baseURL = config.baseURL || '';
this.indent = config.indent || 2;
}
/**
* 格式化JSON数据
*/
formatJSON(data) {
try {
if (typeof data === 'string') {
data = JSON.parse(data);
}
return JSON.stringify(data, null, this.indent);
} catch (error) {
console.error('JSON格式化失败:', error.message);
return data;
}
}
/**
* 从API获取并格式化数据
*/
async fetchAndFormat(url, options = {}) {
const fullUrl = this.baseURL + url;
try {
const response = await axios({
method: options.method || 'GET',
url: fullUrl,
params: options.params,
headers: options.headers,
timeout: options.timeout || 5000
});
return this.formatJSON(response.data);
} catch (error) {
console.error('API请求失败:', error.message);
throw error;
}
}
/**
* 格式化响应数据并保存到文件
*/
async formatAndSave(url, outputPath, options = {}) {
const fs = require('fs').promises;
const formatted = await this.fetchAndFormat(url, options);
await fs.writeFile(outputPath, formatted, 'utf-8');
console.log(`格式化数据已保存到: ${outputPath}`);
}
}
// 使用示例
const formatter = new ApiFormatter({ baseURL: 'https://api.example.com' });
async function main() {
try {
// 格式化JSON字符串
const jsonStr = '{"name":"张三","age":25}';
console.log(formatter.formatJSON(jsonStr));
// 从API获取并格式化
const formattedData = await formatter.fetchAndFormat('/users/1');
console.log(formattedData);
// 保存到文件
await formatter.formatAndSave('/users', './users.json');
} catch (error) {
console.error('处理失败:', error);
}
}
main();
Shell脚本 (使用jq)
#!/bin/bash
# 使用jq格式化JSON
format_json() {
if [ -p /dev/stdin ]; then
# 从管道输入
cat - | jq '.'
elif [ -n "$1" ]; then
# 从文件或字符串输入
if [ -f "$1" ]; then
jq '.' "$1"
else
echo "$1" | jq '.'
fi
else
echo "用法: format_json <文件路径或JSON字符串>"
return 1
fi
}
# 从API获取并格式化
fetch_and_format() {
local url=$1
local output_file=$2
if [ -z "$url" ]; then
echo "请提供API URL"
return 1
fi
# 使用curl获取数据并通过jq格式化
if [ -n "$output_file" ]; then
curl -s "$url" | jq '.' > "$output_file"
echo "格式化数据已保存到: $output_file"
else
curl -s "$url" | jq '.'
fi
}
# 批量格式化
batch_format() {
local input_dir=$1
local output_dir=$2
if [ ! -d "$input_dir" ]; then
echo "输入目录不存在: $input_dir"
return 1
fi
mkdir -p "$output_dir"
for file in "$input_dir"/*.json; do
if [ -f "$file" ]; then
local filename=$(basename "$file")
jq '.' "$file" > "$output_dir/$filename"
echo "已格式化: $filename"
fi
done
}
# 使用示例
# format_json '{"name":"张三","age":25}'
# fetch_and_format "https://api.example.com/data"
Go语言脚本
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
// 格式化JSON数据
func FormatJSON(data []byte, indent string) (string, error) {
var parsed interface{}
if err := json.Unmarshal(data, &parsed); err != nil {
return "", err
}
formatted, err := json.MarshalIndent(parsed, "", indent)
if err != nil {
return "", err
}
return string(formatted), nil
}
// 从API获取并格式化
func FetchAndFormat(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return FormatJSON(body, " ")
}
// 高级格式化器
type APIFomatter struct {
BaseURL string
Client *http.Client
}
func NewAPIFomatter(baseURL string) *APIFomatter {
return &APIFomatter{
BaseURL: baseURL,
Client: &http.Client{},
}
}
func (f *APIFomatter) Process(url string) (string, error) {
fullURL := f.BaseURL + url
resp, err := f.Client.Get(fullURL)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return FormatJSON(body, " ")
}
// 从文件读取JSON并格式化
func FormatFromFile(filePath string) (string, error) {
data, err := ioutil.ReadFile(filePath)
if err != nil {
return "", err
}
return FormatJSON(data, " ")
}
func main() {
// 使用示例
jsonStr := `{"name":"张三","age":25,"hobbies":["reading","swimming"]}`
formatted, err := FormatJSON([]byte(jsonStr), " ")
if err != nil {
fmt.Printf("格式化失败: %v\n", err)
os.Exit(1)
}
fmt.Println(formatted)
}
通用命令工具 (跨平台)
# 使用内置工具格式化
# 1. Python一行命令
echo '{"name":"张三"}' | python -m json.tool
# 2. 读取文件并格式化
python -m json.tool input.json output.json
# 3. Node.js一行命令
node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, 2))" '{"name":"张三"}'
# 4. 使用jq (需要安装)
echo '{"name":"张三"}' | jq '.'
jq '.' input.json
使用建议
- 日常快速格式化:使用Python一行命令
python -m json.tool - 批量处理:使用Python或Go脚本
- 项目集成:集成到CI/CD流程中
- 实时API测试:使用Node.js配合axios
选择哪种方法取决于你的技术栈和使用场景,Python和Node.js的解决方案最为灵活,而Shell脚本最适合Linux环境下的快速处理。
版权声明: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直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播