Home > Net >  How to insert a field at the top of an object?
How to insert a field at the top of an object?

Time:05-12

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?

CodePudding user response:

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"
  }
]
  • Related