使用 jq 动态将 json 对象添加到数组中

use*_*040 5 bash command-line json jq

下面是我的employee.json 文件的模板

{
    "orgConfig": {
        "departments": []
    }
}
Run Code Online (Sandbox Code Playgroud)

其中部门将有如下所示的一系列部门

{
    "name" : "physics",
    "id" : "1234",
    "head" : "abcd"
}
Run Code Online (Sandbox Code Playgroud)

相似地

{
    "name" : "chemistry",
    "id" : "3421",
    "head" : "xyz"
}
Run Code Online (Sandbox Code Playgroud)

所以我想构造的最终数组结构如下

{
    "orgConfig": {
        "departments": [
            {
                "name" : "physics",
                "id" : "1234",
                "head" : "abcd"
            },
            {
                "name" : "chemistry",
                "id" : "3421",
                "head" : "xyz"
            },
            {
                "name" : "Maths",
                "id" : "4634",
                "head" : "jklm"
            }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是我将 json 元素动态添加到 Departments 数组的代码

#!/bin/bash

source department.properties   # will have departments=physiscs,chemistry,Maths,computers .. etc
IFS=',' read -ra NAMES <<< "$departmentsToImport"

position=0
for i in "${NAMES[@]}"; do
    #./jsonfiles will chemistry.json, physics.json, Maths.json etc
    value=`cat ./jsonfiles/$i.json`    

    if [ $position -eq 0 ]
    then
       cat employee.json | jq --arg value "$value" '.orgConfig.departments[0] |= .+ $value' > tmp.json && mv tmp.json employee.json
    else
       cat employee.json | jq --arg position "$position" value "$value" '.orgConfig.departments[$position] |= .+ $value' > tmp.json && mv tmp.json employee.json
    fi
    ((position++))
    rm -rf tmp.json
done

exit $?
Run Code Online (Sandbox Code Playgroud)

但程序抛出以下错误

jq: error (at <stdin>:51): Cannot index array with string "1"
Run Code Online (Sandbox Code Playgroud)

但如果使用直接索引而不是可变位置,那么它就可以正常工作。

cat employee.json | jq --argjson value "$value" '.orgConfig.departments[1] |= .+ $value' > tmp.json && mv tmp.json employee.json 
Run Code Online (Sandbox Code Playgroud)

我不知道我有多少个部门的关键价值图。我无法对索引进行硬编码。对上述问题和动态添加 json 对象到数组有帮助吗?

谢谢

pea*_*eak 4

无需多次调用 jq 即可完成该任务。

类似以下内容就足够了:

jq -s '{orgConfig: {departments: . }}' jsonfiles/*.json
Run Code Online (Sandbox Code Playgroud)

当然,此解决方案假设 .json 文件都包含有效的 JSON。

诀窍是使用 -s (又名 --slurp)选项,因为这会将输入转换为数组。您可能会发现使用 -s 比其他一些方法可以获得更好的运行时间。