Utilizing the sub() function in jq to dynamically modify JSON values based on specified conditions

I'm in need of modifying certain values within JSON data and integrating it into an existing shell script. My aim is to utilize jq for this task, specifically the "sub()" function to trim a portion of a string value.

Executing the following command line:

jq '._meta[][].ansible_ssh_pass | sub(" .*" ; "")'

using the given data will successfully update the value (removing everything after the first space in the data) but only displays the altered value without the complete JSON structure.

Here is an example of the JSON dataset:

{
  "_meta": {
    "hostvars": {
      "10.1.1.3": {
        "hostname": "core-gw1",
        "ansible_user": "",
        "ansible_ssh_pass": "test123 / ena: test2",
        "configsicherung": "true",
        "os": "ios",
        "managementpaket": ""
      }
    }
  }
}

The expected output should resemble the following:

{
  "_meta": {
    "hostvars": {
      "10.1.1.3": {
        "hostname": "core-gw1",
        "ansible_user": "",
        "ansible_ssh_pass": "test123",
        "configsicherung": "true",
        "os": "ios",
        "managementpaket": ""
      }
    }
  }
}

I presume that I need to incorporate some form of "if... then" logic, however, communicating effectively with jq has proven challenging. The manual lacks clarity, and finding a relevant example matching my requirements has been fruitless...

Answer №1

Well, it seems to be a common pattern that once you ask a question publicly, the answer somehow reveals itself! ;)

The following jq-call is exactly what I was looking for:

jq '. ._meta.hostvars[].ansible_ssh_pass |= sub(" .*";"" )'

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

How do I add JSON data to a menu using PHP?

I have a JSON file for my menu structured like this: [{"slug":"index.php","name":"Home"},{"slug":"aboutus","name":"About us","children":[{"slug":"eims","name":"Eims"},{"slug":"vision","name":"Vision"}]},{"slug":"trash","name":"Trash","children":[{"slug":" ...

Mule Server 3.6 Connecting to Anypoint Studio Using the Request Connector

Is there a way to configure the Request Connector to send raw JSON data using the POST method? In my Set Payload transformer, I have the following code: #[{ "productId": #[sessionVars.productId] }] After running my Mule App, I encountered this error: E ...

Error encountered when attempting to retrieve JSON data in JavaScript due to being undefined

A snippet of code that reads and writes JSON data is presented below: var info; $(function () { $.getJSON("data.json", function (d) { info = d; }); $('.btn').click(function () { info['c-type'] = $('#c- ...

Changing a zero-prefixed string into JSON format using Swift 4

When attempting to encode an integer that starts with a 0 into JSON using swift 4, I encountered an issue. Even though I am utilizing a standard JSONSerialization library, I am facing difficulties in serializing the data after converting the string to utf ...

Generating a JSON form to enable users to search for specific dates within a given range by utilizing the "datetime" data type

Currently, I am in the process of developing a form that can search for specific data within a JSON's datetime value. The objective is to retrieve information from the JSON that falls between the first and last dates entered by the user. However, desp ...

Change the input field to uppercase using JavaScript but do not use inline JavaScript

Hey there! I have a basic script set up (see below) with an input field allowing users to enter a query. This query is then sent to a socrata webservice to request specific data, which is displayed in an alert box. So far, everything works smoothly. var l ...

Searching to loop through JSON within a Sequelize / Postgres database query in order to identify a corresponding value

Hello everyone, I'm new here so please bear with me. I'm currently working on a project using Sequelize with PostgresDB in Node and I need to search for a contact by email using findOrCreate function. The email entry is stored in JSON format (se ...

What methods does Json.NET use to implement dependency injection while deserializing?

Is it possible for Newtonsoft.Json to create an object of a class that has no default constructor and uses dependency injection to pass its dependencies? Take the following example: public class SomeFoo { private readonly IFooDependency _dependency; ...

What is the best way to send an HttpPost request to a RESTful web service in order to transmit a URL with parameters that contains an array of values?

I am attempting to call a RESTful webservice in order to retrieve a JSON object. Initially, I made the call using HttpGet and it was successful. The URL structure required for this call looked something like: http://example.com//def.xxx?Name=save&Code= ...

Struggling to encode an array of objects in JSON format

I have a PHP class called Country that I am fetching as an array of objects from a database function call. When I use var_dump($countries), I can see the objects, but when I try to json_encode($countries), it returns empty. class Country implements JsonSe ...

trouble encountered while parsing JSON information using JavaScript

[ [ { "Id": 1234, "PersonId": 1, "Message": "hiii", "Image": "5_201309091104109.jpg", "Likes": 7, "Status": 1, "OtherId": 3, "Friends": 0 } ], [ { "Id": 201309091100159, "PersonI ...

Insert a new key with a value into PostgreSQL only if it does not already exist. If the key exists, update its

Having an issue with updating columns that have NULL values or do not contain a specific key. Here is the code I am trying to run: update A a set a.jsonbcolumn = ('{"key":' 1 '}') I'm currently using postgres version 9.6.3 and u ...

Why isn't this ajax script able to successfully transmit the data?

I'm having some trouble sending a JavaScript variable to a PHP file in order to create a query. Here's the script I've been using, but unfortunately it doesn't seem to be working. Any assistance would be greatly appreciated. <select ...

Narrow down JSON data by chosen element

Utilizing the autocomplete feature, I have created a system to display options based on a JSON file. My current objective is to filter the JSON data according to the selected item. For example, if I select "Roma" from the autocomplete input, I want to dis ...

Unable to retrieve properties post JSON deserialization into dynamic

Struggling with accessing dynamic properties post JSON deserialization. Take a look at the JSON data: { "user" : { "511221" :{ "timestamp" : 1403365646384, "version" : -81317051, "email" : "<a href="/cdn-cgi/l/email-p ...

Struggling to make jquery .ajax cooperate with my PHP JSON data

Question: $.ajax({ type: "POST", url: 'http://blahblah/cow.php', contentType: "application/json", data: { 'guid': '111', 'score': 592, 'initi ...

Minimize the memory footprint of this Pandas script when loading a JSON file and saving it as a pickle

I'm having trouble trying to further optimize memory usage for my program. Essentially, I am parsing JSON log files into a pandas dataframe but encountering the following challenges: The append function is causing substantial memory consumption as i ...

Mastering the Art of Defining JSON Information

I'm curious about how to obtain a single stream of data. Specifically, I want to retrieve the value for ModbusSerial.Port_1.COM.Power from the script. However, I'm unsure of how to write the code for that. I believe it is something similar to: js ...

Employ jq to organize keys within a JSON object based on a specific property

Is there a way to sort the keys of a JSON file in natural order while prioritizing keys listed in the 'required' section? The command below sorts keys in natural order: jq --sort-keys . /tmp/source.json > ./tmp/target.json { "Request ...

Generate a new JSON reply using the current response

I received a JSON response that contains values for week 1, week 2, week 3, and week 4 under the 'week' key, along with counts based on categories (meetingHash) and weeks. I attempted to merge this data using the .reduce method but without succes ...