jsonlinuxshell

Update a list in a JSON file with data from a text file


good afternoon, I have the following dns.json file where I pass the url in Items:

{
        "CallerReference": "1605534454287",
        "Aliases": {
            "Quantity": 2,
            "Items": [
                "tester1.university.com.br",
                "tester2.university.com.br",
                "tester3.university.com.br",
                "end.university.com.br"
            ]
        },

Then, I have a file called list.txt with the following lines:

tester1.university.com.br
tester2.university.com.br
tester3.university.com.br
tester4.university.com.br
tester5.university.com.br
tester6.university.com.br
tester7.university.com.br
tester8.university.com.br

I needed my list.txt file to be read and insert it automatically in dns.json and it looks like this:

{
        "CallerReference": "1605534454287",
        "Aliases": {
            "Quantity": 2,
            "Items": [
                "tester1.university.com.br",
                "tester2.university.com.br",
                "tester3.university.com.br",
                "tester4.university.com.br",
                "tester5.university.com.br",
                "tester6.university.com.br",
                "tester7.university.com.br",
                "tester8.university.com.br",
                "end.university.com.br"
            ]
        }

I have a lot of difficulty in shell, could you guys help me?


Solution

  • Using jq, a tool built specifically for querying and updating JSON:

    jq --rawfile newListStr list.txt '
      [$newListStr | split("\n")[] | select(. != "")] as $newList |
      ["end.university.com.br"] as $suffix |
      .Aliases.Items = $newList + $suffix
    ' <in.json >out.json