使用 jq - bash 将 JSON 解析为数组

1 bash json jq

我的 JSON 看起来像这样:

[
  {
    "file": "aaa.txt",
    "destination": 1
  },
  {
    "file": "bbb.txt",
    "destination": 2
  },
  {
    "file": "ccc.txt",
    "destination": 3
  },
  {
    "file": "ddd.txt",
    "destination": 4
  },
  {
    "file": "eee.txt",
    "destination": 9
  }
]
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用命令 jq 在 bash 中构建一个脚本来获取 JSON 中的项目数,并在第二个命令中使用文件、目标的值。为了实现我使用的第一个

count=$(curl 'http://mypage/json' | jq length)
Run Code Online (Sandbox Code Playgroud)

我正在获取此元素的数量(计数)(在本例中为 5)。接下来我想构建从 5 到 1的 while 循环,将文件值放入 (nomen omen) 文件中(循环中的脚本应创建名为[destination]的文件,其中[file]作为内容(例如:对于第一个文件,应使用 1 来调用) aaa.txt 作为内容)。而且...这是我的问题 - 如何将我的 JSON 放入数组(或其他内容)中?我尝试使用

arr=$(curl 'http://mypage/json' | jq'.[]')
Run Code Online (Sandbox Code Playgroud)

但它把整个 json 合而为一。你能帮我吗?

pea*_*eak 5

使用 jq 解决问题有多种合理的方法,但所有方法的共同点是 jq 只被调用一次。由于bash是标签之一,那么只要“目标”文件名合法,您可能会做比以下更糟糕的事情:

while IFS= read -r destination; do
    IFS= read -r file
    printf "%s" "$file" > "$destination"
done < <(jq -r '.[] | .destination,.file' input.json )
Run Code Online (Sandbox Code Playgroud)

但是,这还假设字段的内容不包含“换行符”或 NUL 字符。如果其中任何一个可能包含文字换行符,请参见下文。

此外,几乎可以肯定的是,检查文件名的有效性和/或处理因写入指定文件名失败而产生的错误。例如,请参阅Windows 和 Linux 目录名称中禁止使用哪些字符?

处理换行符

假设键值不包含 NUL 字符:

while IFS= read -r -d '' destination; do
    IFS= read -r -d '' file
    printf "%s" "$file" > "$destination"
done < <(jq -rj '.[] | map_values(tostring+"\u0000") | .destination,.file' input.json )
Run Code Online (Sandbox Code Playgroud)