Linux

리눅스 명령어 2. jq란?

Somaz 2024. 1. 19. 00:14
728x90
반응형

Overview

이번 글에서는 JSON 데이터를 다루는 데 특화된 커맨드라인 도구인 jq 명령어에 대해 알아보았다.

 


현대 개발 환경에서 JSON 포맷은 API, 로그, 설정 파일 등 다양한 영역에서 표준처럼 사용되며,
jq는 이러한 JSON 데이터를 터미널 상에서 효율적으로 필터링, 가공, 추출하는 데 핵심적인 도구이다.

  • jq는 가볍고 빠르며 설치가 간편한 JSON 파서 및 필터 도구이다.
  • 복잡한 JSON 구조에서 원하는 데이터만 추출하거나, 맵/조건/변환 작업을 간단한 문법으로 처리할 수 있다.
  • 실무에서 API 응답 처리, 로그 필터링, 자동화 스크립트 작성 등 다양한 상황에서 폭넓게 활용된다.

 

 

 

출처 : https://ioflood.com/blog/install-jq-command-linux

 

 

 

 

 


 

 

 

 

jq란?

jq는 JSON 형식의 데이터를 처리하기 위한 커맨드라인 기반의 프로그램이다.

JSON 데이터를 필터링, 매핑, 감소(reduce) 및 변환하는 다양한 연산을 수행할 수 있다.

jq는 작고 가벼워 대부분의 운영체제에서 쉽게 설치하고 사용할 수 있다.

 

 

echo '{"name":"Somaz"}' | jq '.name'

# Output
"Somaz"

 

 

 

 

 

 


 

 

 

 

 

jq 설치 및 사용법

 

jq 설치

# apt
sudo apt-get update
sudo apt-get install jq

# apt(select version)
sudo apt-get install jq=1.5*

# yum
sudo yum install jq

# yum(select version)
sudo yum install jq-1.5

# dnf
sudo dnf install jq

# source code
git clone <https://github.com/stedolan/jq.git>
cd jq
autoreconf -i
./configure
make
sudo make install

# source code(select version)
git clone <https://github.com/stedolan/jq.git>
cd jq
git checkout jq-1.5
autoreconf -i
./configure
make
sudo make install

 

 

 

jq 사용법

 

`jq —help` 명령어를 사용하면 사용법에 대해서 알 수 있다.

jq --help

jq - commandline JSON processor [version 1.6]

Usage:  jq [options]  [file...]
        jq [options] --args  [strings...]
        jq [options] --jsonargs  [JSON_TEXTS...]

jq is a tool for processing JSON inputs, applying the given filter to
its JSON text inputs and producing the filter's results as JSON on
standard output.

The simplest filter is ., which copies jq's input to its output
unmodified (except for formatting, but note that IEEE754 is used
for number representation internally, with all that that implies).

For more advanced filters see the jq(1) manpage ("man jq")
and/or <https://stedolan.github.io/jq>

Example:

        $ echo '{"foo": 0}' | jq .
        {
                "foo": 0
        }

Some of the options include:
  -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 ;
  --argjson a v    set variable $a to JSON value ;
  --slurpfile a f  set variable $a to an array of JSON texts read from ;
  --rawfile a f    set variable $a to a string consisting of the contents of ;
  --args           remaining arguments are string arguments, not files;
  --jsonargs       remaining arguments are JSON arguments, not files;
  --               terminates argument processing;

Named arguments are also available as $ARGS.named[], while
positional arguments are available as $ARGS.positional[].

 

 

 

기본 사용법

# 단일 요소 출력
echo '{"name": "Somaz", "age": 31}' | jq '.name'
# Output
"Somaz"

# 전체 객체 출력
echo '{"name": "Somaz", "age": 31}' | jq '.'
# Output
{
  "name": "Somaz",
  "age": 31
}

# 특정 키로 필터링
echo '[{"name": "Somaz", "age": 31}, {"name": "오9Lee", "age": 28}]' | jq '.[] | select(.age < 30)'
# output
{
  "name": "오9Lee",
  "age": 28
}

# 오징어 필터링
echo '[{"name": "오9Lee", "face": "오징어"}, {"name": "오9Lee", "face": "갑오징어"}]' | jq '.[] | select(.face | test("^오징어"))'
# output
{
  "name": "오9Lee",
  "face": "오징어"
}

# 오징어 포함된 모든 사람 필터링
echo '[{"name": "전산직", "face": "오징어"}, {"name": "오9Lee", "face": "갑오징어"}]' | jq '.[] | select(.face | test("오징어"))'
# output
{
  "name": "오9Lee",
  "face": "오징어"
}
{
  "name": "오9Lee",
  "face": "갑오징어"
}

 

 

 

고급 필터

# 매핑과 변환
echo '[{"name": "Somaz", "age": 31}, {"name": "오9Lee", "age": 28}]' | jq '.[] | {personName: .name, yearOfBirth: (2024 - .age + 1)}'
# output(Korean age)
{
  "personName": "Somaz",
  "yearOfBirth": 1994
}
{
  "personName": "오9Lee",
  "yearOfBirth": 1997
}

# 조건부 출력
echo '[{"name": "Somaz", "age": 31}, {"name": "오9Lee", "age": 28}]' | jq 'map(if .age > 30 then .name else empty end)'
# output
[
  "Somaz"
]

 

 

 

유용한 옵션

 

`-r` (Raw Output): 출력 결과에서 따옴표를 제거한다.

echo '{"name": "Somaz", "age": 31}' | jq -r '.name'
# output
Somaz

 

 

 

`-c` (Compact Output): 각 JSON 객체를 한 줄로 압축하여 출력한다.

echo '[{"name": "Somaz", "age": 31}, {"name": "오9Lee", "age": 25}]' | jq -c '.[]'
# output
{"name":"Somaz","age":31}
{"name":"오9Lee","age":25}

 

 

`--arg` (Arguments): 스크립트에 외부에서 변수를 전달한다.

# data.json 생성
cat <<EOF > data.json
[
  {"name": "Somaz", "age": 31},
  {"name": "Jane", "age": 25},
  {"name": "Doe", "age": 22},
  {"name": "John", "age": 45}
]
EOF

jq --arg name "Somaz" '.[] | select(.name == $name)' data.json
# output
{
  "name": "Somaz",
  "age": 31
}

 

 

 

 

 

실무에서 유용한 jq 고급 팁

 

 

slurp 옵션 (-s)

 

여러 JSON 라인을 배열로 묶어서 처리할 때 사용한다.

cat files/*.json | jq -s '.'
  • 여러 개의 JSON 문서를 하나의 배열로 묶어 후처리할 수 있어, 대용량 로그 처리 시 유용하다.

 

 

 

파일에서 JSON 키 값을 추출하는 실전 예

cat config.json | jq '.services[].name'
  • 중첩 배열 안의 키 값들을 손쉽게 추출할 수 있다.

 

 

 

test 정규표현식 활용

jq '.[] | select(.name | test("^somaz"))' data.json
  • 이름이 "somaz"로 시작하는 항목만 필터링할 수 있다. 

 

 

 

 

다중 조건 처리

jq '.[] | select(.age > 25 and .name == "Somaz")' data.json
  • `and, or, not` 등 논리 연산자를 통해 복합 조건 필터링이 가능하다.

 

 

 

JSON 키 정렬 및 포맷 정리

jq -S '.' config.json
  • `-S` 옵션은 키를 정렬해서 JSON을 보기 좋게 정리합니다. Git 관리 중인 JSON 파일의 변경 추적에도 유용하다.

 

 

 

JSON 중첩구조에서 특정 값만 추출

jq '.items[] | .metadata.name' pods.json
  • Kubernetes의 리소스 목록처럼 중첩된 구조에서 특정 필드를 일괄 추출할 때 자주 사용된다.

 

 

 

jq를 쉘 스크립트와 연계

name=$(jq -r '.user.name' config.json)
echo "사용자 이름은 $name 입니다"
  • `jq -r` 과 변수 바인딩으로 쉘 자동화 스크립트에서 JSON 값을 직접 활용할 수 있다.

 

 

 

 

 

 


 

 

 

마무리

JSON은 개발 및 운영 환경에서 빠르게 표준 데이터 형식으로 자리 잡았고,
jq는 그러한 JSON 데이터를 다루는 가장 직관적이고 강력한 커맨드라인 도구 중 하나다.

 

 

이 글을 통해 배운 주요 내용은 다음과 같다.

  • jq 설치 방법 및 기본 문법 (.key, select, map, test 등)
  • JSON 구조에서 특정 조건에 따라 데이터를 필터링하는 방법
  • --arg, -r, -c 등의 실용적인 옵션 활용법
  • 다양한 예제를 통한 실전 연습: 나이 조건 필터링, 키 이름 변경, 정규식 검색 등

 

 

jq를 익히면 복잡한 JSON도 두려울 것이 없다.
마치 grep이나 awk처럼, 당신의 터미널 도구 상자에 꼭 추가해두자.

자주 쓰는 jq 명령은 별도의 alias나 함수로 등록해두면 업무 속도를 더욱 높일 수 있다.

 

 

 

 

 

 

 


Reference

 

 

728x90
반응형