jq 실무 명령어 치트시트: 터미널 JSON 데이터 필터링·변환

💡 핵심 요약 (Executive Summary)

본 가이드는 print jq 핵심 가이드 및 실전 아키텍처의 핵심 개념, 실전 구성 명령어 및 아키텍처 베스트 프랙티스를 다룹니다. 클라우드 네이티브 및 인프라 엔지니어링 실무에 즉시 활용 가능하도록 체계적으로 정리했습니다.

📑 Table of Contents
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
배열 전체요소 중 키의 밸류가 일치한 요소가 전체의 몇번째에 있는지 확인
bash
#결과로 출력된 LineNumber -1이 배열의 순서가 된다.
$jsonSTDOUT | jq -r '.[].$key' | grep -n '$value'
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
특정 JSON 형식으로 가공하여 출력
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 *