0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

curlのレスポンスJSONを一瞬で整形する3つの方法

0
Posted at

API の動作確認で curl を叩いたら、レスポンスが 1 行に圧縮された JSON で返ってきて読めない。開発中に毎日のように遭遇する場面だと思う。

この記事では、curl のレスポンスを整形する方法を 3 つ紹介する。

方法 1: jq にパイプする

最も定番の方法。jq がインストールされていればこれが一番速い。

curl -s https://api.example.com/users | jq .

出力:

{
  "status": 200,
  "data": {
    "users": [
      {
        "id": 1,
        "name": "田中太郎"
      }
    ]
  }
}

jq はフィルタリングもできるので、特定のフィールドだけ取り出したいときにも便利。

curl -s https://api.example.com/users | jq '.data.users[].name'

ただし、jq が入っていない環境(CI のミニマルコンテナ等)では使えない。

方法 2: python -m json.tool

Python がインストールされていれば追加パッケージなしで使える。

curl -s https://api.example.com/users | python3 -m json.tool

jq ほどのフィルタ機能はないが、整形するだけならこれで十分。Python 2 系しかない環境でも python -m json.tool で動く。

方法 3: ブラウザで整形する

curl の結果をクリップボードにコピーして、ブラウザの整形ツールに貼り付ける方法。コマンドラインに慣れていないチームメンバーと共有するときに便利。

FormatArc の JSON Formatter はブラウザ内だけで処理が完結し、入力データをサーバーに送信しない。業務データを貼っても安心して使える。

curl-json-format.png

手順:

  1. curl の出力をコピー
  2. 入力欄に貼り付け
  3. 「実行」を押す

整形結果はそのままコピーして Slack や Issue に貼れる。

使い分け

方法 メリット デメリット
jq 速い。フィルタもできる インストールが必要
python -m json.tool 追加インストール不要 フィルタ不可
ブラウザツール 非エンジニアとも共有しやすい ターミナルから離れる

普段は jq、入っていなければ python、チーム共有や目視確認なら FormatArc という使い分けがおすすめ。

おまけ: curlの出力を直接整形して保存

curl -s https://api.example.com/users | jq . > response.json

後で見返す用途なら、整形してファイルに保存しておくと楽。

まとめ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?