【发布时间】:2023-04-02 21:40:01
【问题描述】:
下面是我的employee.json文件的模板
{
"orgConfig": {
"departments": []
}
}
部门将有如下的一系列部门
{
"name" : "physics",
"id" : "1234",
"head" : "abcd"
}
类似
{
"name" : "chemistry",
"id" : "3421",
"head" : "xyz"
}
所以我要构建的最终数组结构如下
{
"orgConfig": {
"departments": [
{
"name" : "physics",
"id" : "1234",
"head" : "abcd"
},
{
"name" : "chemistry",
"id" : "3421",
"head" : "xyz"
},
{
"name" : "Maths",
"id" : "4634",
"head" : "jklm"
}
]
}
}
下面是我将 json 元素动态添加到部门数组的代码
#!/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 $?
但程序抛出以下错误
jq: error (at <stdin>:51): Cannot index array with string "1"
但是如果使用直接索引而不是可变位置,那么它工作正常。
cat employee.json | jq --argjson value "$value" '.orgConfig.departments[1] |= .+ $value' > tmp.json && mv tmp.json employee.json
我不知道我有多少部门的键值图。我无法对索引进行硬编码。对上述问题有什么帮助并动态地将 json 对象添加到数组中?
谢谢
【问题讨论】:
标签: json bash command-line jq