'How to insert a field at the top of an object?
This is my code
element='{"x":"zero"}'
example='[
{
"a":"one",
"b":"two",
"c":"three"
},
{
"d":"four",
"e":"five",
"f":"six"
}]'
jq --argjson el "$element" '.[] += $el' <<< $example
It currently outputs
[
{
"a":"one",
"b":"two",
"c":"three",
"x":"zero"
},
{
"d":"four",
"e":"five",
"f":"six",
"x":"zero"
}
]
But i would like to have the "x":"zero" be the first element of all array elements, not the last.
Inverting the variable with the .[] iterator would make no sense. Any idea how this can be done?
Solution 1:[1]
In order for the new field to appear at the top, the object that holds it must appear first in the addition statement. For example:
$ jq --argjson el "$element" 'map($el + .)' <<< $example
[
{
"x": "zero",
"a": "one",
"b": "two",
"c": "three"
},
{
"x": "zero",
"d": "four",
"e": "five",
"f": "six"
}
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
