jq는 JSON 입력에 filter를 적용해 선택, 변환, 집계하는 command-line processor다.
.는 입력값을 그대로 출력한다.jq –version으로 확인한다.jq 공식 다운로드 문서가 안내하는 배포판 repository package를 설치한다.
sudo apt-get update sudo apt-get install jq
sudo dnf install jq
공식 다운로드 문서는 Fedora package를 안내하지만 RHEL용 DNF/YUM repository 명령은 별도로 제시하지 않는다. RHEL에서 배포판 package를 사용할 수 없다면 공식 다운로드 페이지에서 CPU architecture에 맞는 Linux binary와 release checksum을 확인한다.
brew install jq
winget install jqlang.jq
jq --version jq --help
jq [OPTIONS] FILTER [FILE...] jq [OPTIONS] --args FILTER [STRING...] jq [OPTIONS] --jsonargs FILTER [JSON_TEXT...]
jq [OPTIONS] FILTER [FILE…]jq –args FILTER [STRING…]jq –jsonargs FILTER [JSON_TEXT…]FILE을 생략하면 standard input에서 JSON text stream을 읽는다.-n, –null-input: 입력을 읽지 않고 null에 filter를 한 번 실행한다.-R, –raw-input: JSON parsing 없이 각 입력 line을 string으로 읽는다.-s, –slurp: 모든 입력값을 하나의 array로 모은 뒤 filter를 한 번 실행한다.–stream: 큰 JSON을 path와 leaf value의 stream 형태로 처리한다.–seq: ASCII RS로 구분된 JSON text sequence를 읽고 쓴다.-c, –compact-output: 결과 하나를 한 line의 compact JSON으로 출력한다.-r, –raw-output: string 결과를 JSON quote 없이 출력한다.–raw-output0: string 결과 뒤에 newline 대신 NUL을 출력한다. newline을 포함할 수 있는 filename 처리에 유용하며 jq 1.7 이상이 필요하다.-j, –join-output: –raw-output처럼 출력하되 결과 사이에 newline을 넣지 않는다.-a, –ascii-output: non-ASCII 문자를 escape한 ASCII JSON으로 출력한다.-S, –sort-keys: object key를 정렬한다.-C, –color-output, -M, –monochrome-output: 색상 출력을 강제하거나 비활성화한다.–tab, –indent N: pretty-print indentation을 조정한다. N은 7 이하여야 한다.–arg NAME VALUE: string value를 $NAME에 안전하게 전달한다.–argjson NAME JSON_TEXT: parsing한 JSON value를 $NAME에 전달한다.–slurpfile NAME FILE: file의 JSON text들을 array로 읽어 변수에 넣는다.–rawfile NAME FILE: file 전체를 string으로 읽어 변수에 넣는다.-f, –from-file FILE: command line 대신 file에서 jq program을 읽는다.-L, –library-path DIRECTORY: module 검색 경로를 지정한다. 사용하면 built-in 검색 목록은 사용하지 않는다.-e, –exit-status: 마지막 결과가 false 또는 null이면 1, 결과가 없으면 4, 그 밖에는 0을 반환한다.-V, –version: version을 출력한다.–build-configuration: build 설정을 출력한다. 출력 형식은 안정된 API가 아니다.-h, –help: 도움말을 출력한다.–: option parsing을 끝내고 뒤의 값을 positional argument로 취급한다.., .name, .nested.value: 입력 전체 또는 object field 선택.items[], .items[]?: array/object value 순회. ?는 type·missing error를 억제한다.select(CONDITION): 조건이 참인 값만 통과map(FILTER): array 각 항목에 filter 적용keys, length, type: key, 길이, JSON type 확인{name: .user.name, id}: 기존 값을 새 object로 구성. id는 id: .id의 축약형이다.[FILTER]: filter가 만든 모든 결과를 array로 수집한다.to_entries, from_entries, with_entries(FILTER): object와 key/value entry array 사이를 변환한다.sort_by(FILTER), group_by(FILTER), unique_by(FILTER): array를 기준값으로 정렬, 그룹화, 중복 제거한다.add, min, max, length: collection 집계에 사용한다.//는 왼쪽 결과가 false 또는 null일 때 오른쪽 default를 사용한다.printf '%s\n' '{"name":"jq","version":"1.8"}' | jq . printf '%s\n' '{"name":"jq","version":"1.8"}' | jq -r '.name' jq '.items[] | .name' data.json
기존 command record:
go env -json | jq .GOAUTH
jq '.users[] | select(.active == true) | {id, name}' users.json jq '[.items[] | select(.price >= 100)] | sort_by(.price)' catalog.json
user_name='alice' enabled='true' jq -n --arg name "$user_name" --argjson enabled "$enabled" \ '{name: $name, enabled: $enabled}'
–arg, JSON value는 –argjson으로 전달하면 quoting 오류와 filter injection 위험을 줄일 수 있다. –argjson 값은 유효한 JSON이어야 한다.
jq -s 'add' part-*.json printf '%s\n' alpha beta gamma | jq -R -s 'split("\n")[:-1]' jq -n --slurpfile config config.json '$config'
if jq -e '.healthy == true' status.json >/dev/null; then echo 'healthy' else echo 'not healthy or invalid input' fi
-e의 exit code 1은 JSON parse error와 같지 않다. script에서 원인을 구분해야 하면 jq의 실제 exit code와 standard error를 함께 확인한다.
jq 1.7 이상에서는 NUL-delimited output을 사용할 수 있다.
jq --raw-output0 '.files[]' manifest.json | while IFS= read -r -d '' file; do printf '%s\n' "$file" done
-f FILE이나 module로 분리한다.NO_COLOR가 비어 있지 않으면 기본 color output을 끈다. -C는 이를 명시적으로 다시 활성화할 수 있다.JQ_COLORS는 terminal color 구성을 바꾼다. 자동화에서는 환경별 색상 차이를 피하려고 -M을 명시하는 편이 안전하다.-L DIRECTORY로 제어한다. 이 option을 주면 default search list가 대체되므로 필요한 module path를 모두 지정한다.-R이 필요할 수 있다.-s를 검토한다.type, keys, .로 중간 구조를 확인한다.? 또는 default operator //를 사용하되, 실제 schema 오류를 무조건 숨기지 않는다.jq '.name' file.json..jq file과 -f 사용을 검토한다.–arg 또는 –argjson으로 전달한다.–raw-output0는 jq 1.7에서 추가되었으므로 jq 1.6에서는 사용할 수 없다.jq.exe를 WSL, MSYS2 또는 Cygwin에서 사용할 때 newline 변환을 피하려면 -b, –binary가 필요할 수 있다.