Unten ist die Vorlage meiner employee.json Dateidynamisch hinzufügen JSON-Objekt in einem Array mit jq
{
"orgConfig": {
"departments": []
}
}
wo Abteilungen Reihe von Abteilungen wie unter
{
"name" : "physics",
"id" : "1234",
"head" : "abcd"
}
ähnlich
{
"name" : "chemistry",
"id" : "3421",
"head" : "xyz"
}
haben
so die endgültige Array-Struktur, die ich erstellen möchte, ist wie folgt
{
"orgConfig": {
"departments": [
{
"name" : "physics",
"id" : "1234",
"head" : "abcd"
},
{
"name" : "chemistry",
"id" : "3421",
"head" : "xyz"
},
{
"name" : "Maths",
"id" : "4634",
"head" : "jklm"
}
]
}
}
Unten ist der Code, wo ich die json Array-Elemente zu einem Abteilung dynamisch unter Fehler
#!/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 $?
aber Programm wirft
jq: error (at <stdin>:51): Cannot index array with string "1"
Aber wenn Verwendung direkter Index anstelle der variablen Position am Hinzufügen dann funktioniert es gut.
cat employee.json | jq --argjson value "$value" '.orgConfig.departments[1] |= .+ $value' > tmp.json && mv tmp.json employee.json
Ich weiß nicht, wie viele Schlüsselwertkarten von Abteilungen ich habe. Ich kann den Index nicht hart codieren. Irgendwelche Hilfe zu oben genanntem Problem und dynamisch JSON-Objekt in das Array hinzufügen?
Dank
Dank @peak, bekam neue Anforderungen auf der Grundlage Lösung u oben gab. – user1876040