Converting personal injury claims into configuration maps with the help of jq

Here is my input:

{
  "apiVersion": "apps/v1",
  "kind": "Deployment",
  "spec": {
    "template": {
      "spec": {
        "containers": [
          {
            "volumeMounts": [
              {
                "mountPath": "/var/www/html",
                "name": "shared"
              },
              {
                "mountPath": "/var/www/html/LocalSettings.d/LocalSettings.override.php",
                "name": "movies-wikibase-claim1"
              },
              {
                "mountPath": "/var/www/html/img/wikibase_logo.png",
                "name": "movies-wikibase-claim2"
              }
            ]
          }
        ],
        "volumes": [
          {
            "name": "shared",
            "persistentVolumeClaim": {
              "claimName": "shared"
            }
          },
          {
            "name": "movies-wikibase-claim1",
            "persistentVolumeClaim": {
              "claimName": "movies-wikibase-claim1"
            }
          },
          {
            "name": "movies-wikibase-claim2",
            "persistentVolumeClaim": {
              "claimName": "movies-wikibase-claim2"
            }
          }
        ]
      }
    }
  }
}

I'd like to modify mount paths ending with a file extension to point to corresponding 'configMaps' objects, replacing the existing 'persistentVolumeClaim' associations.

The desired outcome should be:


    {
    ...
                "volumeMounts": [
                  {
                    "mountPath": "/var/www/html",
                    "name": "shared"
                  },
                  {
                    "mountPath": "/var/www/html/LocalSettings.d/LocalSettings.override.php",
                    "name": "movies-wikibase-localsettings-override-php",
                    "subPath": "LocalSettings.override.php"
                  },
                  {
                    "mountPath": "/var/www/html/img/wikibase_logo.png",
                    "name": "movies-wikibase-wikibase-logo-png",
                    "subPath": "wikibase_logo.png"
                  }
                ]
              }
            ],
            "volumes": [
              {
                "name": "shared",
                "persistentVolumeClaim": {
                  "claimName": "shared"
                }
              },
              {
                "configMap": {
                  "defaultMode": 420,
                  "name": "movies-wikibase-localsettings-override-php"
                },
                "name": "movies-wikibase-localsettings-override-php"
              }
              {
                "configMap": {
                  "defaultMode": 420,
                  "name": "movies-wikibase-wikibase-logo-png"
                },
                "name": "movies-wikibase-wikibase-logo-png"
              }
    

I've attempted some modifications but have not yet achieved the desired result:

cat movies-wikibase-deployment.json| 
   jq -r '((.spec.template.spec.containers[].volumeMounts[]?|select(.mountPath|test("(\\.[^.]+)$")))|={mountPath: .mountPath, name: ((.name|split("-claim")|.[0]) + "-" + (.mountPath|split("/")|last|gsub("_";"-")|gsub("\\.";"-")|ascii_downcase)), subPath: (.mountPath|split("/")|last)})|(((.spec.template.spec.containers[].volumeMounts[]?|select(.mountPath|test("(\\.[^.]+)$")).name) ) as $toto|.spec.template.spec.volumes+=[{configMap: {defaultMode: 420, name: $toto}, name: $toto}])'

EDIT: A more readable version of the code could be written as follows:

jq -r '(
         (.spec.template.spec.containers[].volumeMounts[]?|
          select(.mountPath|test("(\\.[^.]+)$")))|=
          {mountPath: .mountPath, name: ((.name|split("-claim")|.[0]) + "-" + (.mountPath|split("/")|last|gsub("_";"-")|gsub("\\.";"-")|ascii_downcase)), subPath: (.mountPath|split("/")|last)}
       )|
        (
         ((.spec.template.spec.containers[].volumeMounts[]?|select(.mountPath|test("(\\.[^.]+)$")).name) ) as $toto|
         .spec.template.spec.volumes+=[{configMap: {defaultMode: 420, name: $toto}, name: $toto}])'  movies-wikibase-deployment.json

Answer №1

To enhance efficiency and avoid redundant transformations on the same data source in multiple locations, I suggest creating a lookup table (using INDEX) to store and retrieve values for array item modifications:

.spec.template.spec |= (

  INDEX(.containers[].volumeMounts[]
    | {id: .name, subPath: (.mountPath / "/")[-1]}
    | .name = (.id | .[:index("claim")])
            + (.subPath | gsub("[_.]";"-") | ascii_downcase);
    select(.subPath | test("[.][^.]+$")).id
  ) as $lookup
  
  # The $lookup table with sample input:
  # 
  # {
  #   "movies-wikibase-claim1": {
  #     "id": "movies-wikibase-claim1",
  #     "subPath": "LocalSettings.override.php",
  #     "name": "movies-wikibase-localsettings-override-php"
  #   },
  #   "movies-wikibase-claim2": {
  #     "id": "movies-wikibase-claim2",
  #     "subPath": "wikibase_logo.png",
  #     "name": "movies-wikibase-wikibase-logo-png"
  #   }
  # }

  | .containers[].volumeMounts[] |= last(., {mountPath} + (
      $lookup[.name] | values | {name, subPath}
    ))

  | .volumes[] |= last(., (
      $lookup[.name] | values | {configMap: {defaultMode: 420, name}, name}
    ))

)
{
  "apiVersion": "apps/v1",
  "kind": "Deployment",
  "spec": {
    "template": {
      "spec": {
        "containers": [
          {
            "volumeMounts": [
              {
                "mountPath": "/var/www/html",
                "name": "shared"
              },
              {
                "mountPath": "/var/www/html/LocalSettings.d/LocalSettings.override.php",
                "name": "movies-wikibase-localsettings-override-php",
                "subPath": "LocalSettings.override.php"
              },
              {
                "mountPath": "/var/www/html/img/wikibase_logo.png",
                "name": "movies-wikibase-wikibase-logo-png",
                "subPath": "wikibase_logo.png"
              }
            ]
          }
        ],
        "volumes": [
          {
            "name": "shared",
            "persistentVolumeClaim": {
              "claimName": "shared"
            }
          },
          {
            "configMap": {
              "defaultMode": 420,
              "name": "movies-wikibase-localsettings-override-php"
            },
            "name": "movies-wikibase-localsettings-override-php"
          },
          {
            "configMap": {
              "defaultMode": 420,
              "name": "movies-wikibase-wikibase-logo-png"
            },
            "name": "movies-wikibase-wikibase-logo-png"
          }
        ]
      }
    }
  }
}

See Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deconstructing a JSON Structure

I'm currently developing a D3 damage per second (DPS) calculator and encountering an issue with a JSON object. The JSON object I receive looks like this: {"Sockets":{"min":1,"max":1}, "Dexterity_Item":{"min":165,"max":165}, "Durability_Cur":{"min":58 ...

Develop an HTML table using either JSON or jQuery in Javascript

JavaScript is a bit of a mystery to me right now - I could really use some assistance in overcoming this obstacle that has me pulling my hair out! I'm struggling with constructing HTML code using JSON data. It's just not clicking for me at the m ...

Guide to accessing and utilizing environment-specific values during configuration stage

My goal is to deploy my web application across multiple environments. With Continuous Integration, I can automate the generation of a config.json file for each specific environment. This file will include important URLs that need to be used. { "baseUrl" ...

Leveraging JSON in Play 2

Currently, I am working on developing a straightforward application that allows me to manage different users by creating, reading, updating, and deleting their information. Initially, I set up a basic UI-based view, controller, and model which are function ...

Spark failing to produce output when parsing a newline delimited JSON file

The JSON file shown below is formatted with newline delimiters. [ {"name": "Vishay Electronics", "specifications": " feature low on-resistance and high Zener switching speed\n1/lineup from small signal produ ...

Merging two JSON objects in MULE: A step-by-step guide

I recently delved into MULE and encountered a challenge with combining two JSONs. One is received from an HTTP post request while the other is set as the Payload in a sub flow. I attempted using a custom Transformer without success. Can anyone provide gu ...

"Enhance your web application with dynamic drop-down selection using Spring, Ajax

In my JSP file, I have a script that populates the list of states based on the selected country. The script fetches data from the controller and is supposed to display the list of states. However, after calling the controller method, the alert "received da ...

"Troubleshooting: Vue JS Axios Post Request Not Passing Data to PHP Server

After successfully uploading an image in Vue JS and sending a POST request to a Laravel Route, the JSON response from the API is displayed on the client side as expected. However, there seems to be an issue with retrieving this response in PHP, as it retur ...

Script on Google Sheets fails to update with every event trigger

I came across a JSON import script while exploring. /** * Retrieves all the rows in the active spreadsheet that contain data and logs the * values for each row. * For more information on using the Spreadsheet API, see * https://developers.google.com/a ...

I'm puzzled as to why my HTTP request in Node.js is returning an empty body

Currently, I am facing an issue where I am sending a HTTP request to a server and expecting a response that contains all the necessary information. However, when attempting to parse the body using .parseJSON(), an exception is thrown indicating that the ...

Using jQuery to load and parse a JSON file stored on a local system

I am a beginner in scripting languages and recently searched for ways to load and parse JSON files using jQuery. I found helpful resources on Stack Overflow. The JSON file I am working with is called new.json. { "a": [ {"name":"avc"}, ...

Utilizing SharedPreferences within an AsyncTask class to showcase information

I'm facing a challenge here. I need to access a SharedPreferences value within an AsyncTask class to display JSON data, but I'm encountering an issue. Whenever I try to access it, I get the error message "JSON parsing error : No Value lokasi". Be ...

Created JSON object providing the number as a string value

I am currently facing an issue with a Vue method where it generates a JSON object from user input values before making an axios put request. The problem I'm encountering is that the JSON object generated converts numbers into strings, causing issues w ...

FrisbyJS and JSONSchema encounter a SchemaError when the specified schema does not exist

I utilize frisbyjs along with modules like jsonschema and jasmine-node for execution. There is a particular schema named test.json: { "error": { "type": "array", "minItems": 2, "items": { "type": "object", "properties": { ...

``We can showcase API data using various endpoints and then present it on a web page using

Hello from Argentina! I'm new to programming and recently started a Flask project. I've successfully displayed information from an API using one endpoint and rendered it with Flask. However, I'm now facing the challenge of displaying informa ...

Troubleshooting an issue with updating JSON data in PostgreSQL

There is a table with a json column called "stats" that has the value: {"countValue":0} I am attempting to update this value by: UPDATE my_table SET stats = jsonb_set(stats, '{countValue}', 1); However, I am encountering the following error: ...

Ruby on Rails JSON API - flawless JSON without any errors

When I am displaying an array of ActiveRecord items, each has been processed through the valid? method so errors are already defined. The rendering of the array is done as follows: render json: array_of_objects I have ActiveModelSerializers.confi ...

Is it possible to locate/create a JSON keyname in a jQuery $.post function?

Currently, I am diving back into the world of Ajax after a long break. At this point, I have created a page that is able to fetch a dynamic number of elements (initially ten, but this can change), and populates each of the ten divs with relevant text. In ...

The dynamically created array length is indicating as null

Although this question has been asked numerous times, most answers are in plain JavaScript. I have a function that generates an array with product data. This array is then utilized in another function to retrieve new data via JSON. $(function(){ var p ...

What are the steps to create an iOS app for reading articles that includes offline caching?

I am currently in the process of developing an application for reading articles. The data is being fetched from a server in JSON format and loaded into UITableView and UIWebView. Each article consists of images, videos, and text. I am aiming to implement o ...