Ely
Ely

Reputation: 11152

Add a new entry to a Json after or before a specified existing entry with jq

I have the following input and I want to below output using jq.

I would like to add

Example input:

{
  "fachbereich": "qp",
  "produktTyp": "PRODUKT_ANFRAGE_V1",
  "name": "Produkt Anfrage",
  "kurzName": "anfrage",
  "gueltigAb": "2019-01-01T00:00:00.000",
  "gueltigBis": "2022-12-31T00:00:00.000",
  "inhaltsverzeichnis": {
    "versandumfang": "auftragsverwaltung/versandumfang",
    "dokumentenerzeugung": "dokumentenerzeugung"
  }
}

Example output:

{
  "fachbereich": "qp",
  "produktTyp": "PRODUKT_ANFRAGE_V1",
  "name": "Produkt Anfrage",
  "kurzName": "anfrage",
  "gueltigAb": "2019-01-01T00:00:00.000",
  "gueltigBis": "2022-12-31T00:00:00.000",
  "zeiterfassungAktiviert": true,
  "inhaltsverzeichnis": {
    "versandumfang": "auftragsverwaltung/versandumfang",
    "dokumentenerzeugung": "dokumentenerzeugung",
    "zeiterfassung": "zeiterfassung"
  },
}

I managed to do the second part but am not clear about how to go about the first part.

Command: jq '.zeiterfassungAktiviert += "zeiterfassung" | .inhaltsverzeichnis.zeiterfassung += "zeiterfassung"'

The result is as follows:

{
  "fachbereich": "qp",
  "produktTyp": "PRODUKT_ANFRAGE_V1",
  "name": "Produkt Anfrage",
  "kurzName": "anfrage",
  "gueltigAb": "2019-01-01T00:00:00.000",
  "gueltigBis": "2022-12-31T00:00:00.000",
  "inhaltsverzeichnis": {
    "versandumfang": "auftragsverwaltung/versandumfang",
    "dokumentenerzeugung": "dokumentenerzeugung",
    "zeiterfassung": "zeiterfassung"
  },
  "zeiterfassungAktiviert": true
}

As you can see it is added to the end of the root object. I would like to specify the position somehow, ideally without having to convert into array and convert back if possible but rather by saying please add entry after/before a specified key.

Upvotes: 1

Views: 96

Answers (1)

peak
peak

Reputation: 116640

For the first part, it helps to have a helper function:

def insertkv($afterkey; $key; $value):
  def insertafter($ix; $x): .[0:1+$ix] + [$x] + .[1+$ix:];

  to_entries
  | insertafter( map(.key) | index($afterkey);  {$key, $value})
  | from_entries;

Versions

The above is intended for use with jq 1.5 or later. Some minor fiddling is required for earlier versions.

Upvotes: 2

Related Questions