举个例子
[root @ test~] #mysql -uroot -p'123123'-e“从mysql.user中选择用户,主机;”
+-------------------+-----------+
| user | host |
+-------------------+-----------+
| root | % |
| test | % |
| sqlaudit_test_mon | % |
| sysbase_test | % |
| mysql.session | localhost |
| mysql.sys | localhost |
+-------------------+-----------+
如何使搜索结果快速转换为json格式你可以使用jq工具或python等
[
{
"user":"root","host":"%"},
{
"user":"test","host":"%"},
{
"user":"sqlaudit_test_mon","host":"%"},
{
"user":"sysbase_test","host":"%"},
{
"user":"mysql.session","host":"localhost"},
{
"user":"mysql.sys","host":"localhost"}
]
我只想知道如何快速将搜索结果发送给json,谢谢!用户jq或python脚本更好,它可以让我搜索结果为json格式。
只需在SELECT中执行此操作,而不是将另一个程序拉入管道。 MySQL有JSON functions。这里感兴趣的是JSON_ARRAYAGG()
和JSON_OBJECT()
。就像是:
SELECT json_arrayagg(json_object('user', user, 'host', host)) FROM mysql.user;
应该这样做,加上不打印那个花哨的ascii艺术所需要的东西。
这是一个全jq解决方案,假设这样的调用:
jq -Rcn -f program.jq sql.txt
特别注意-R(“原始输入”)和-n选项。
def trim: sub(" *$";"") | sub("^ *";"");
# input: an array of values
def objectify($headers):
. as $in
| reduce range(0; $headers|length) as $i ({}; .[$headers[$i]] = ($in[$i]) ) ;
def preprocess:
select( startswith("|") )
| split("|")
| .[1:-1]
| map(trim) ;
reduce (inputs|preprocess) as $in (null;
if . == null then {header: $in}
else .header as $h
| .table += [$in|objectify($h)]
end )
| .table