jq CLI Sheet: JSON Data Filtering & Slicing

๐Ÿ’ก jq CLI Sheet: JSON Data Filtering & Slicing โ€” Executive Summary

Technical architectural analysis, practical configuration manifests, and deployment instructions for jq CLI Sheet: JSON Data Filtering & Slicing.

Exec
main
bash
#json to pretty
$jsonSTDOUT | jq ''
echo '\"foo\":\"bar\"' | jq ''
curl http://foo.bar.com/api/v1/test | jq ''

#๋ฐฐ์—ด ๋‚ด ํŠน์ • ์ˆœ๋ฒˆ์„ ์ถœ๋ ฅ
$jsonSTDOUT | jq '.[$n]'

#๋ฐฐ์—ด ๋‚ด ๋ชจ๋“  ์š”์†Œ ๋‚ด์˜ ํŠน์ • ํ‚ค๋ฅผ ์ถœ๋ ฅ
$jsonSTDOUT | jq '.[].$key'
$jsonSTDOUT | jq '.[].$key1.$key2'

#์•„์›ƒํ’‹ ์ถœ๋ ฅ์‹œ quote ์ œ๊ฑฐ
$jsonSTDOUT | jq -r ''
query
bash
#๋ฐฐ์—ด ๋‚ด ๋ชจ๋“  ์š”์†Œ์ค‘ queryํ•œ ํ‚ค์˜ ๋ฐธ๋ฅ˜๊ฐ€ ์ผ์น˜ํ•  ๋•Œ์— ์ถœ๋ ฅ
$jsonSTDOUT | jq '.[] | select(.$key == "$value")'
#์ด์ค‘ ๋ฆฌ์ŠคํŠธ ํ•„ํ„ฐ๋ง
$jsonSTDOUT | jq '.token.catalog[] | {type: .type, name: .name, ep: (.endpoints[] | select(.interface == "public") | .url) }'
command
bash
#path ํ™•์ธ
$jsonSTDOUT | jq 'paths'
$jsonSTDOUT | jq -c 'paths'

#์ธํ’‹ํŒŒ์ผ ํ™•์ธ
$jsonSTDOUT | jq 'input_filename'

#key ๋ฐฐ์—ด ์ถœ๋ ฅ
$jsonSTDOUT | jq '$json_path | keys'
flags
bash
#์ถœ๋ ฅ ์••์ถ•
  -c               compact instead of pretty-printed output;
#
  -n               use `null` as the single input value;
#
  -e               set the exit status code based on the output;
  -s               read (slurp) all inputs into an array; apply filter to it;
#"" ์ œ๊ฑฐ
  -r               output raw strings, not JSON texts;
  -R               read raw strings, not JSON texts;
  -C               colorize JSON;
  -M               monochrome (don't colorize JSON);
  -S               sort keys of objects on output;
  --tab            use tabs for indentation;
  --arg a v        set variable $a to value <v>;
  --argjson a v    set variable $a to JSON value <v>;
  --slurpfile a f  set variable $a to an array of JSON texts read from <f>;
  --rawfile a f    set variable $a to a string consisting of the contents of <f>;
  --args           remaining arguments are string arguments, not files;
  --jsonargs       remaining arguments are JSON arguments, not files;
  --               terminates argument processing;
Features
Check which element of the array has the same key value
bash
#๊ฒฐ๊ณผ๋กœ ์ถœ๋ ฅ๋œ LineNumber -1์ด ๋ฐฐ์—ด์˜ ์ˆœ์„œ๊ฐ€ ๋œ๋‹ค.
$jsonSTDOUT | jq -r '.[].$key' | grep -n '$value'
Output index.yaml
bash
# .entries ์•„๋ž˜์— ์žˆ๋Š” ๋ชจ๋“  key๊ฐ’์„ ๋ฐฐ์—ด๋กœ ์ถœ๋ ฅ
cat index.yaml | yq -o json | jq '.entries | keys'

# .entries ์•„๋ž˜์— ์žˆ๋Š” ๋ชจ๋“  key๊ฐ’์„ ๋ฐฐ์—ด๋กœ ์ถœ๋ ฅ ํ›„ ๋ฐฐ์—ด๋‚ด์šฉ๋ฌผ๋งŒ ์ถœ๋ ฅ ๋ฐ double-quotes ์ œ๊ฑฐ
cat index.yaml | yq -o json | jq '.entries | keys[]' -r
Processed and output in specific JSON format
bash
cat cmp.yaml | yq -ojson | jq -r '{"name":.metadata.name, "path":.spec.source.path}'

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *