jq: error: Cannot iterate over null (null) 해결: 경로부터 확인한다jq: error: Cannot iterate over null (null) Fix: Check the Path First
jq 에서 Cannot iterate over null (null) 을 만난 독자가 원인이 경로 오타·깊이 착오인지 서버의 오류 응답인지 가려 고치게 한다.
없는 키는 오류 없이 null 이 되고 펼치는 순간 오류가 난다. keys·type·paths 로 모양을 보고 경로를 고치면 풀렸고, .item[]? 같은 가리기는 오타도 종료 코드 0 의 빈 출력으로 만들었다.
같은 입력에 jq 'map_values(type)' 와 jq -c 'paths(type=="array")' 를 돌려 배열이 있는 경로를 찾고, 오류가 난 .items[] 를 그 경로로 바꾼 뒤 출력이 기대한 목록과 같은지 대조한다.
한 줄 요약:
Cannot iterate over null (null)은.items[]가 가리킨 자리가null이라 펼칠 것이 없다는 뜻이므로,?로 가리기 전에 JSON 의 실제 모양을 보고 경로를 고친다.
바로 할 것: 오류가 난 입력에 아래 두 줄을 돌려 최상위 키의 종류와 배열이 있는 경로를 보고, 오류가 난 .items[] 를 그 경로로 바꾼다.
jq -c 'map_values(type)' data.json # {"message":"string",...} 처럼 키마다 종류가 나온다
jq -c 'paths(type=="array")' data.json # ["data","items"] 가 나오면 .data.items[], 아무것도 안 나오면 배열이 없는 응답(원인 2 등)
오류는 이렇게 보인다
jq '.item[] | .name' data.json 처럼 펼치는 순간 종료 코드 5 와 함께 아래 한 줄이 나온다. 뒤의 data.json:1 은 입력이 파일이면 파일 이름과 줄, 파이프(|)로 받았으면 <stdin>:1 이다. 줄 번호는 입력에 따라 달라지고 아래 curl 예에서는 <stdin>:0 이었다.
jq: error (at data.json:1): Cannot iterate over null (null)
jq 매뉴얼은 .foo[] 가 .foo | .[] 와 같다고 적는다. .foo 가 없는 키를 가리키면 오류가 아니라 null 이 되고, 그 null 에 [] 를 붙이는 순간 터진다. 그래서 진짜 실수는 오류가 가리키는 [] 앞의 경로에 있다. 값이 문자열·숫자·불리언이어도 같은 모양의 오류가 나고 괄호 안에 값이 찍혔다.
Cannot iterate over string ("none")
Cannot iterate over number (3)
Cannot iterate over boolean (false)
오류 문구와 아래 표의 모든 명령은 jq 1.6, 1.7.1, 1.8.1 에서 같은 출력과 종료 코드를 냈다. curl 을 쓴 시험은 1.7.1 로만 돌렸다.
원인 1: 경로가 한 칸 틀렸다
입력이 {"total_count":2,"items":[{"name":"a"},{"name":"b"}]} 일 때 결과는 이렇다.
| 명령 | 입력 | 결과 |
|---|---|---|
.items[] | .name |
위 입력 | "a" "b" |
.item[] | .name |
위 입력 (s 빠짐) |
오류, 종료 5 |
.data.items[] | .name |
위 입력 (한 단계 더 들어감) | 오류, 종료 5 |
.items[] | .name |
{"data":{"items":[…]}} (한 단계 덜 들어감) |
오류, 종료 5 |
.data.items[] | .name |
{"data":{"items":[…]}} |
"a" "b" |
오타와 깊이 착오는 똑같은 문구로 나오니 문구만 봐서는 가를 수 없다. 모양을 직접 본다. keys 는 최상위 키를, .item | type 은 그 자리의 종류를 말해 준다.
$ jq -c 'keys' data.json # ["items","total_count"] <- item 이 아니라 items
$ jq '.item | type' data.json # "null"
$ jq -c 'paths(type=="array")' nested.json # ["data","items"]
paths(type=="array") 는 배열이 있는 모든 경로를 한 줄씩 내므로, 이 입력처럼 키로만 이어진 경로는 출력을 그대로 .data.items[] 로 옮겨 적으면 끝난다. 경로 중간에 숫자가 끼면 그 칸은 배열의 몇 번째라는 뜻이다.
{"data":[{"items":[{"name":"a"},{"name":"b"}]}]} 에서 ["data",0,"items"] 가 나왔고, .data[0].items[] 와 모든 칸을 도는 .data[].items[] 는 a, b 를 냈으며 숫자를 뺀 .data.items[] 는 Cannot index array with string "items" 로 막혔다.
원인 2: 서버가 목록 대신 오류 본문을 줬다
API 호출 결과를 curl -s URL | jq '.items[]' 로 받는데 토큰이 틀리면 서버가 {"message":"Bad credentials"} 같은 오류 객체를 돌려주는 일이 있다(시험한 로컬 서버가 그렇게 했다). 이 객체에는 items 키가 없어서 원인 1과 같은 문구가 난다. 로컬 서버가 401 과 이 본문을 주게 해서 시험했다.
$ curl -s http://127.0.0.1:5911/bad | jq -r '.items[] | .name'
jq: error (at <stdin>:0): Cannot iterate over null (null)
$ curl -s http://127.0.0.1:5911/bad | jq -c .
{"message":"Bad credentials"}
curl 은 401 응답도 종료 코드 0 으로 끝내므로 파이프 앞에서는 실패가 드러나지 않는다. jq 를 빼고 본문과 상태 코드를 먼저 본다.
code=$(curl -s -o body.json -w '%{http_code}' URL); echo "status=$code"; jq -c . body.json
# 오류 응답: status=401 / {"message":"Bad credentials"}
# 정상 응답: status=200 이고 jq -r '.items[] | .name' body.json 이 a, b 를 낸다
curl -f 는 4xx 에서 본문을 버리고 curl: (22) The requested URL returned error: 401 을 내지만, 파이프의 종료 코드는 마지막 명령인 jq 의 0 이다(curl -fsS URL | jq -r '.items[] | .name' 가 실제로 0). set -o pipefail 을 켜야 22 가 나왔다. --fail-with-body(curl 7.76 이상, 로컬 man 페이지 기준) 는 본문을 남기므로 같은 jq 오류가 다시 났다.
jq '.[] | .name' 으로 바꿔 시험하면 다른 오류가 난다. .[] 가 객체의 값인 "Bad credentials" 를 펼쳐서 그 문자열에 .name 을 붙이게 되므로 Cannot index string with string "name" 이 나온다. 이 문구가 보이면 .[] 가 펼친 값이 객체가 아니라 문자열이라는 뜻이니 입력의 모양부터 본다.
가려도 되는 때와 안 되는 때
검색하면 ? 와 // [] 를 붙이라는 답이 먼저 나온다. 오류는 사라지지만 오타도 함께 사라진다. 아래는 각 줄의 입력으로 돌린 결과다.
| 명령 | 입력 | 출력 | 종료 |
|---|---|---|---|
.item[]? | .name |
items 가 있는 정상 목록 (오타) |
없음 | 0 |
(.item // [])[] | .name |
같은 입력 (오타) | 없음 | 0 |
.items[]? | .name |
{"message":"Bad credentials"} |
없음 | 0 |
.items[] | .name |
{"items":[]} (정말 빈 목록) |
없음 | 0 |
.items[] |
{"items":"none"} |
오류 (string) | 5 |
.items[]? |
{"items":"none"} |
없음 | 0 |
(.items // [])[] |
{"items":"none"} |
오류 (string) | 5 |
(.flag // [])[] |
{"flag":false} |
없음 | 0 |
오타, 오류 본문, 정말 빈 목록이 전부 “출력 없음, 종료 0” 으로 똑같아진다. ? 는 값이 문자열이어도 삼키고 // 는 null 과 false 만 대체해서 문자열은 그대로 오류가 났다. 매뉴얼도 // 가 false 나 null 이 아닌 값만 통과시킨다고 적는다.
판단 기준은 하나다. 경로를 위 두 줄로 확인해 맞다는 것을 안 뒤에, 그 키가 선택 항목이라 없는 것이 정상일 때만 ? 나 // [] 를 붙인다. jq 에 -e 를 주면 출력이 없을 때 종료 코드 4 가 나서 스크립트가 알아챌 수 있다. 다만 정말 빈 목록 {"items":[]} 에서도 4 가 나서(-e 없이는 0), 빈 목록과 오타는 이것으로도 가를 수 없다.
비슷해 보이는 다른 오류
최상위가 목록이면 .items[] 는 Cannot iterate over null 이 아니라 Cannot index array with string "items" 로 막힌다. [{"name":"a"},{"name":"b"}] 이면 jq '.[] | .name' 이 "a" "b" 를 냈고, jq 'type, length' 로 "array" 와 2 를 먼저 볼 수 있다. 문구가 Cannot index … 로 시작하면 값이 null 이 아니라 종류가 틀린 것이고, 처방의 첫 단계는 같다. 모양부터 본다.
시험 범위와 한계
macOS 26.6.2 arm64 에서 jq 1.7.1(시스템), 1.8.1, 1.6 으로 시험했다. 1.6 은 jqlang 릴리스의 x86_64 바이너리라 Rosetta 로 돌았다. 시험 전체를 두 번 실행해 출력이 같았다. 입력은 직접 만든 작은 JSON 과 로컬 서버가 401 을 주는 curl 응답(curl 8.7.1)이다. 줄마다 JSON 이 이어진 입력(ndjson)의 종료 코드 해석은 다루지 않았다. 실제 GitHub·AWS 같은 외부 API 응답, 큰 입력의 속도, gojq·jaq 같은 다른 구현, Windows·Linux 빌드는 시험하지 않았다.
세 줄 요약
- 없는 키는 오류 없이
null이 되고[]로 펼치는 순간Cannot iterate over null (null)이 나므로, 오류 줄보다 앞의 경로를 의심한다. jq 'map_values(type)'와jq -c 'paths(type=="array")'로 모양을 보면 오타·깊이 착오를 고칠 수 있고, 서버 오류 본문이면 jq 를 빼고 상태 코드와 본문부터 본다.?와// []는 오타·오류 본문·빈 목록을 모두 “출력 없음, 종료 0” 으로 만들므로 경로를 확인한 뒤 선택 키에만 쓴다.
Help a reader who hit Cannot iterate over null (null) in jq tell whether the cause is a path typo or wrong depth, or an error response from the server, and fix it.
A missing key becomes null without any error, and the error only appears when you expand it. Looking at the shape with keys, type and paths and fixing the path worked, while hiding it with .item[]? turned a typo into empty output with exit code 0.
Run jq 'map_values(type)' and jq -c 'paths(type=="array")' on the same input to find where the array lives, replace the failing .items[] with that path, and check that the output matches the list you expected.
Contents
One-line summary:
Cannot iterate over null (null)means the place.items[]points at isnull, so there is nothing to expand; look at the real shape of the JSON and fix the path before you hide the error with?.
Do this first: Run the two lines below on the input that failed to see the type of each top-level key and where the arrays are, then replace the failing .items[] with that path.
jq -c 'map_values(type)' data.json # prints the type of each key, like {"message":"string",...}
jq -c 'paths(type=="array")' data.json # if ["data","items"] appears, use .data.items[]; if nothing appears, the response has no array (cause 2 and others)
What the error looks like
When a filter such as jq '.item[] | .name' data.json expands the value, jq exits with code 5 and prints the line below. The data.json:1 at the end is the file name and line when the input is a file, and <stdin>:1 when it came through a pipe (|). The line number depends on the input; in the curl example below it was <stdin>:0.
jq: error (at data.json:1): Cannot iterate over null (null)
The jq manual says .foo[] is equivalent to .foo | .[]. If .foo points at a key that does not exist, the result is null, not an error, and the error only fires when [] is applied to that null. So the real mistake is in the path in front of the [] that the error points at. If the value is a string, number or boolean, the same kind of error appears with the value printed in parentheses.
Cannot iterate over string ("none")
Cannot iterate over number (3)
Cannot iterate over boolean (false)
The error message and every command in the table below gave the same output and exit code on jq 1.6, 1.7.1 and 1.8.1. The tests that use curl were run on 1.7.1 only.
Cause 1: the path is off by one step
The input is {"total_count":2,"items":[{"name":"a"},{"name":"b"}]} and the results look like this.
| Command | Input | Result |
|---|---|---|
.items[] | .name |
the input above | "a" "b" |
.item[] | .name |
the input above (missing s) |
error, exit 5 |
.data.items[] | .name |
the input above (one level too deep) | error, exit 5 |
.items[] | .name |
{"data":{"items":[…]}} (one level too shallow) |
error, exit 5 |
.data.items[] | .name |
{"data":{"items":[…]}} |
"a" "b" |
A typo and a wrong depth produce exactly the same message, so the message alone cannot tell them apart. Look at the shape directly. keys lists the top-level keys, and .item | type tells you what kind of value sits at that spot.
$ jq -c 'keys' data.json # ["items","total_count"] <- items, not item
$ jq '.item | type' data.json # "null"
$ jq -c 'paths(type=="array")' nested.json # ["data","items"]
paths(type=="array") prints every path that holds an array, one per line, so for a path made only of keys, as in this input, you can copy the output straight into .data.items[] and you are done. When a number appears in the middle of a path, that step means the nth element of an array.
On {"data":[{"items":[{"name":"a"},{"name":"b"}]}]} the output was ["data",0,"items"]; .data[0].items[] and .data[].items[], which walks every element, both gave a and b, while .data.items[] with the number removed was stopped by Cannot index array with string "items".
Cause 2: the server returned an error body instead of a list
When you pipe an API result with curl -s URL | jq '.items[]' and the token is wrong, the server sometimes returns an error object such as {"message":"Bad credentials"} (the local server I tested did). That object has no items key, so you get the same message as in cause 1. I tested this with a local server that returns a 401 and that body.
$ curl -s http://127.0.0.1:5911/bad | jq -r '.items[] | .name'
jq: error (at <stdin>:0): Cannot iterate over null (null)
$ curl -s http://127.0.0.1:5911/bad | jq -c .
{"message":"Bad credentials"}
curl also ends with exit code 0 on a 401 response, so the failure is not visible in front of the pipe. Look at the body and the status code first, without jq.
code=$(curl -s -o body.json -w '%{http_code}' URL); echo "status=$code"; jq -c . body.json
# error response: status=401 / {"message":"Bad credentials"}
# normal response: status=200, and jq -r '.items[] | .name' body.json prints a and b
curl -f drops the body on a 4xx and prints curl: (22) The requested URL returned error: 401, but the exit code of the pipe is that of the last command, jq, which is 0 (curl -fsS URL | jq -r '.items[] | .name' really exited 0). Only with set -o pipefail turned on did it exit 22. --fail-with-body (curl 7.76 or later, according to the local man page) keeps the body, so the same jq error came back.
If you change the filter to jq '.[] | .name', you get a different error. .[] expands the value "Bad credentials" of the object, so .name gets applied to that string and you get Cannot index string with string "name". When you see this message, it means the value .[] expanded is a string rather than an object, so look at the shape of the input first.
When hiding it is fine and when it is not
Search results tell you to add ? or // [] first. The error disappears, but so does the typo. Below are the results with the input shown on each line.
| Command | Input | Output | Exit |
|---|---|---|---|
.item[]? | .name |
a normal list that has items (typo) |
none | 0 |
(.item // [])[] | .name |
same input (typo) | none | 0 |
.items[]? | .name |
{"message":"Bad credentials"} |
none | 0 |
.items[] | .name |
{"items":[]} (a genuinely empty list) |
none | 0 |
.items[] |
{"items":"none"} |
error (string) | 5 |
.items[]? |
{"items":"none"} |
none | 0 |
(.items // [])[] |
{"items":"none"} |
error (string) | 5 |
(.flag // [])[] |
{"flag":false} |
none | 0 |
A typo, an error body and a genuinely empty list all become the same “no output, exit 0”. ? swallows even a string value, while // replaces only null and false, so a string still raised the error. The manual also says // lets through only values that are neither false nor null.
The rule is one thing. Confirm the path with the two lines above, and only then, when the key is optional and being absent is normal, add ? or // []. If you give jq -e, it exits with code 4 when there is no output, so a script can notice. But it also exits 4 on a genuinely empty list {"items":[]} (without -e it is 0), so even this cannot tell an empty list from a typo.
A similar-looking error
When the top level is a list, .items[] is stopped not by Cannot iterate over null but by Cannot index array with string "items". For [{"name":"a"},{"name":"b"}], jq '.[] | .name' gave "a" "b", and jq 'type, length' shows "array" and 2 first. When the message starts with Cannot index …, the value is not null but the wrong kind of value, and the first step of the fix is the same: look at the shape first.
Test scope and limits
I tested on macOS 26.6.2 arm64 with jq 1.7.1 (system), 1.8.1 and 1.6. The 1.6 binary was the x86_64 build from the jqlang release, so it ran under Rosetta. I ran the whole test twice and the output was identical. The inputs were small JSON files I wrote myself and a curl response from a local server that returns a 401 (curl 8.7.1). I did not cover how exit codes behave for input with one JSON value per line (ndjson). I did not test real external API responses such as GitHub or AWS, speed on large inputs, other implementations such as gojq or jaq, or Windows and Linux builds.
Three-line summary
- A missing key becomes
nullwithout an error, and the moment you expand it with[]you getCannot iterate over null (null), so suspect the path before the line the error points at. - Looking at the shape with
jq 'map_values(type)'andjq -c 'paths(type=="array")'lets you fix typos and wrong depths, and if the server returned an error body, look at the status code and body without jq first. ?and// []turn typos, error bodies and empty lists alike into “no output, exit 0”, so use them only on optional keys after you have confirmed the path.