【MySQL】JSON型のカラムを見やすい形式で表示する
2021/12/23
問題
MySQLでJSON型のカラムを普通にSELECT文で表示すると見づらい
> select body from response \G
*************************** 1. row ***************************
body: {"body": {"deviceList": [{"deviceId": "500291B269BE", "deviceName": "Living Room Humidifier", "deviceType": "Humidifier", "hubDeviceId": "000000000000", "enableCloudService": true}], "infraredRemoteList": [{"deviceId": "02-202008110034-13", "deviceName": "Living Room TV", "remoteType": "TV", "hubDeviceId": "FA7310762361"}]}, "message": "success", "statusCode": 100}
例でSwitchBotのAPIのレスポンスを使用した(https://github.com/OpenWonderLabs/SwitchBotAPI)
このくらいの量だったら読めなくもないけど、実際はもっと長いレスポンスを格納する時もある
解決方法
JSON_PRETTY
というユーティリティ関数があるので、それを使うと見やすい形式で表示してくれる
select JSON_PRETTY(body) from response \G
*************************** 1. row ***************************
JSON_PRETTY(body): {
"body": {
"deviceList": [
{
"deviceId": "500291B269BE",
"deviceName": "Living Room Humidifier",
"deviceType": "Humidifier",
"hubDeviceId": "000000000000",
"enableCloudService": true
}
],
"infraredRemoteList": [
{
"deviceId": "02-202008110034-13",
"deviceName": "Living Room TV",
"remoteType": "TV",
"hubDeviceId": "FA7310762361"
}
]
},
"message": "success",
"statusCode": 100
}
MySQL 5.7.8からJSON型をサポートしたので、おそらくそれ以降なら使えるはず
ちなみにJSON型のカラム以外でもJSON形式になっていれば使えた
補足
今回使ったテーブルのCREATE文とINSERT文
create table response (body json);
desc response;
+-------+------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------+------+-----+---------+-------+
| body | json | YES | | NULL | |
+-------+------+------+-----+---------+-------+
1 row in set (0.002 sec)
insert into response values ('{"statusCode":100,"body":{"deviceList":[{"deviceId":"500291B269BE","deviceName":"Living Room Humidifier","deviceType":"Humidifier","enableCloudService":true,"hubDeviceId":"000000000000"}],"infraredRemoteList":[{"deviceId":"02-202008110034-13","deviceName":"Living Room TV","remoteType":"TV","hubDeviceId":"FA7310762361"}]},"message":"success"}');