跳到内容
🛠️ToolsShed

SQL 结果转 JSON 转换器

将SQL查询结果(MySQL/PostgreSQL CLI输出)转换为JSON。支持制表符和管道符分隔格式。

关于此工具

SQL to JSON Converter 能把 MySQL 或 PostgreSQL 在终端中打印的表格转换成整洁的 JSON 数组。无需手动重新输入控制台的查询结果,你就能得到可直接用于 API、测试数据或脚本的结构化数据。

粘贴 CLI 结果表格,工具会返回一个 JSON 数组,其中每一行都成为以列名为键的对象。它非常适合填充测试数据、快速制作 API 模拟数据,或在不使用数据库客户端的情况下把查询结果搬进代码。

它同时支持以制表符分隔和以竖线分隔的表格输出,因此 MySQL 和 PostgreSQL 的 CLI 格式都能使用。所有处理都在你的浏览器本地完成,查询数据绝不会上传到任何地方。

常见问题

代码实现

import json
import re

def parse_mysql_output(text):
    """Parse MySQL CLI pipe-separated output to JSON."""
    lines = text.strip().splitlines()
    # Filter out separator lines (+---+) and empty lines
    data_lines = [l for l in lines if l.strip() and not re.match(r'^\s*[+\-]+', l)]
    if len(data_lines) < 2:
        return []

    # Split by pipe and strip whitespace
    def split_row(line):
        return [c.strip() for c in line.split('|') if c.strip() != '']

    headers = split_row(data_lines[0])
    rows = [split_row(l) for l in data_lines[1:]]

    return [dict(zip(headers, row)) for row in rows]

# Example: MySQL output
mysql_output = """
+----+-------+-------+
| id | name  | score |
+----+-------+-------+
|  1 | Alice |    95 |
|  2 | Bob   |    87 |
+----+-------+-------+
"""

result = parse_mysql_output(mysql_output)
print(json.dumps(result, indent=2))

Comments & Feedback

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