Nightscape
Nightscape

Reputation: 464

Add attributes to all json objects with a regex

I have a json array:

{
    "Tabelle1": [
        {
            "Nr.": "1",
            "Firma": "Alba Reisen/Versicherungen/Darlehen H. Kajtazi",
            "Rechtsform": "EIU",
            "Sitz": "Rapperswil-Jona",
            "Kanton": "SG",
            "UID": "CHE‑101.868.757"
        },
        {
            "Nr.": "2",
            "Firma": "Alybaba - Schischa Laden, Aly",
            "Rechtsform": "EIU",
            "Sitz": "Wil (SG)",
            "Kanton": "SG",
            "UID": "CHE‑102.012.121"
        },
        {
            "Nr.": "3",
            "Firma": "Bluamawerkstatt zur Linde Marianne Bislin-Lieberherr",
            "Rechtsform": "EIU",
            "Sitz": "Pfäfers",
            "Kanton": "SG",
            "UID": "CHE‑217.602.289"
        },
    ]
}

i want to add to every object a attribute and a value which look like this:

"X": ""

in the end the objects would look like this:

    {
        "Nr.": "2",
        "Firma": "Alybaba - Schischa Laden, Aly",
        "Rechtsform": "EIU",
        "Sitz": "Wil (SG)",
        "Kanton": "SG",
        "UID": "CHE‑102.012.121",
        "X":""
    },

I managed to filter the last attribute of my json with this regex, but i think i am still far away from a solution:

"UID\s*([^\n\r]*)

I am using the search and replace feature of VSCode witch supports regex filtering.

Upvotes: 1

Views: 1117

Answers (3)

rioV8
rioV8

Reputation: 28733

  1. Select "UID"
  2. Use menu Selection > Select All Occurrences
  3. Press keys End Comma Enter
  4. Type "X": ""

Upvotes: 2

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38522

I think you are making things complicated by using regex here. You can use any programming language to append that X element with "" easily to each object inside Tabelle1. I used Javascript here for the demo. If you still need the regex then you can try this one.

const json = {
  "Tabelle1": [{
      "Nr.": "1",
      "Firma": "Alba Reisen/Versicherungen/Darlehen H. Kajtazi",
      "Rechtsform": "EIU",
      "Sitz": "Rapperswil-Jona",
      "Kanton": "SG",
      "UID": "CHE‑101.868.757"
    },
    {
      "Nr.": "2",
      "Firma": "Alybaba - Schischa Laden, Aly",
      "Rechtsform": "EIU",
      "Sitz": "Wil (SG)",
      "Kanton": "SG",
      "UID": "CHE‑102.012.121"
    },
    {
      "Nr.": "3",
      "Firma": "Bluamawerkstatt zur Linde Marianne Bislin-Lieberherr",
      "Rechtsform": "EIU",
      "Sitz": "Pfäfers",
      "Kanton": "SG",
      "UID": "CHE‑217.602.289"
    },
  ]
}
json['Tabelle1'].forEach(e => e['X'] = "");
console.log(json);

Upvotes: 1

In case you use regex, you should use capturing group.

^(\s+)("UID".*$)
  • (\s+): Group1: matches leading spaces
  • ("UID".*$): Group2: matches content of UID.

After, you use following substitution (visual-studio-code).

$1$2\n$1"X": ""

Upvotes: 1

Related Questions