値のみを印刷し、nullを除く

値のみを印刷し、nullを除く

jqを使用してjson出力を印刷しようとしていますが、nullが表示されます。印刷せずにaccess_keyとSecret_keyのみを印刷する方法はnull

$ cat sample.json | jq '.'

{
  "access_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
{
  "secret_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

$ cat sample.json | jq -e ".access_key"  
xxxxxxxxxxxxxxxxxxxxxxxxx
null

Secret_keyでも同じことが起こります。

「生出力」を使用するとエラーが発生します。

$ cat sample.json | jq -r ".access_key" | jq --raw-output 'select(type == "string")'
parse error: Invalid numeric literal at line 2, column 0

私もこれを試しました:

$ cat sample.json | jq -re ".access_key" | jq 'select(.go != null) | .geo' > geo-only.json
parse error: Invalid numeric literal at line 2, column 0

ベストアンサー1

入力したjsonが正しくありません。あなたはそれを使用することができますhttps://jsonlint.com行って確認してみてください。

次のように変更して動作させることができます。

[{
    "access_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}, {
    "secret_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}]

またはjq回避策があります。

cat sample.json | jq "..|objects|select(.access_key) | .access_key"

簡単なツールを使用することをお勧めしますJSONJq以上。高速ではありませんが、使いやすく直感的で、機能も優れています。

jsonはパラメータを使用してこの問題を処理します-g

-g、--グループ

隣接するオブジェクトをオブジェクトの配列にグループ化するか、隣接する配列を単一の配列に連結します。

$ cat sample.json | json -ag access_key
1234

おすすめ記事