What is the best way to extract JSON values from a response using Groovy?

In my Jenkins Shared Library, I have implemented the following function:

/* This function lists all the groups */

 

def list_groups(server_url, each_group_name, authentication){

    def groups_url  = server_url + "/api/v1/groups"  

    def response =  httpRequest consoleLogResponseBody: true,

                    contentType: 'APPLICATION_JSON',

                    customHeaders: [[maskValue: false, name: 'Authorization', value: authentication]],

                    httpMode: 'GET', ignoreSslErrors: true, responseHandle: 'NONE', url: groups_url,

                    validResponseCodes: '100:599'

 

    if(response.status == 404){

        throw new Exception("The server URL was not found! Please provide a correct server URL.")

    }

    else{

            if(response.status == 400 ||  response.status == 403){

                        throw new Exception("Invalid Access token or Access token expired!")

        }

    }

 

    def result = readJSON text: """${response.content}"""

}

=====================================================================

The response I am receiving is:

Response Code: HTTP/1.1 200 OK

Response:

[{"id":2,"name":"Default User"},{"id":3,"name":"fos"},{"id":4,"name": "kXR"},{"id":5,"name": "Sgh"},{"id":6,"name":"ksn"},{"id":7,"name":"ALb"}]

Success: Status code 200 falls within the accepted range: 100-599

Requirement:

I need to extract and store the last output from the JSON body (id & name) ---> {"id":7,"name":"ALb"} from the response using groovy.

Answer №1

To begin, it is essential to convert the response String into a JSON object. This can be achieved by utilizing Jenkins' built-in method readJSON, or an alternative like JsonSlurperClassic. Subsequently, JSON path expressions can be employed to retrieve specific values. Refer to the sample below.

def jsonObject = readJSON text: response.getContent()
def user_id = jsonObject.id[-1]
def user_name = jsonObject.name[-1]
echo "User ID: $user_id | User Name: $user_name"

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

What is the reason behind the TypeScript HttpClient attempting to interpret a plain text string as JSON data?

When utilizing Angular TypeScript, I have implemented the following approach to send a POST request. This request requires a string parameter and returns a string as the response. sendPostRequest(postData: string): Observable<string> { let header: ...

Submitting an image blob to a database using the FormBuilder

I'm facing an issue with uploading a file blob into the same DB as my form. Here is my form: this.accForm = this.formBuilder.group({ team_leader: ['', Validators.required], hotel_name: ['', Validators.required], address: [&a ...

PHP issues caused by Ajax form compatibility

I'm currently working on developing an upload website and I've encountered some challenges while trying to implement an upload progress bar. The Ajax form in my scripts seems to be causing issues with the PHP code, preventing the file from being ...

A guide on how to efficiently retrieve all images stored in a specific directory

I attempted to showcase all the images from a single directory using jQuery, but unfortunately it is not functioning as expected. My folder setup includes an 'images' folder and a 'js' folder. I followed this question on Stack Overflow ...

Having trouble incorporating this JavaScript code into customizing my material design chips

Having trouble integrating this code snippet into a React.js project. When I try to add it as a function, I get an error message saying that $ is not defined. I've experimented with different methods, but so far, I haven't been successful in gett ...

What is the method for retrieving the data from an XMLHttpRequest response?

Is there a way to use jQuery to query the result of an XMLHttpRequest? For example, let's say I have this code snippet: $.get('somepage.htm', function(data) { console.log($("div.abc").text()); }); The issue is that $("div.abc").text() i ...

Challenging questions about Ember.js: managing save and delete operations for hasMany relationships

Currently, I am working on my first Ember project which is a quiz generator. I have successfully implemented the functionality to create, edit, and delete quizzes, and save them to local storage. However, I am facing challenges in saving/deleting quiz ques ...

PHP move_uploaded_file() function encountering an issue

As a newcomer to PHP, I am exploring the move_uploaded_file() function. I initiate an HTTP POST request from JavaScript/jQuery to a PHP file hosted on a Microsoft Azure server. The request includes an audio blob like so... mediaRecorder.ondataavailab ...

Make the child div images disappear gradually and at the same time, make an overlapping parent div image appear using Javascript

Check out my attempt at solving this challenge on jsfiddle: http://jsfiddle.net/oca3L32h/ In the scenario, there are 3 divs within a main div. Each of these divs contains an image and they overlap each other. By using radio buttons, the visibility of the ...

Angular 4: Retrieving the selected element's object from a collection of elements

In my x.component.html file, I have a list of objects that are being displayed in Bootstrap cards like this: <div *ngFor="let item of items | async"> <div class="row"> <div class="col-lg-6"> <div class="card ...

Inaccurate inference of pipe and compose function types within TypeScript

I have created functions called pipe and compose which can combine two functions into a new one, with the only difference being the order in which they are called when applied to an argument. Although both functions are generic, I am having trouble ensuri ...

How can one retrieve specific key values from all random IDs in a Realtime Database, using Firebase functions with JavaScript?

Looking to retrieve the locations of all users in order to find nearest friends Here is an example of my Firebase Real-time database structure: ---> users ---> userRandomId ---> name: location :[12312,213123] ---> ...

Guide on accessing APIs for individual elements in an array

Currently utilizing Next.js / React.js and making use of this API to retrieve information about a specific country. Within the response, there exists an array called borders, as shown below: borders: [ "CAN", "MEX", ], There is ...

How can I employ angular animations to smoothly transition components in and out of a <router-outlet> in Angular 2, following the initial loading process?

Currently, the code is functioning correctly (but not exactly how I intended haha). The animation successfully fades in when the page loads initially and is first initialized. However, the animations do not trigger when navigating routes within the app aft ...

Struggling to get my JavaScript function for calculating one rep max to work, need some help figuring out the issue

I have been working on a one rep max calculator using the Epley Formula. However, when I try to call the function, it returns as undefined. I have utilized the parameters weight and reps, both of which are parsed as integers, believing that they would be e ...

Dealing with the notorious AngularJS error: $rootScope:infdig while using ng-style function within ng-repeat

I'm currently working on an animation for displaying phrases randomly on the main page of a website, complete with fade and translate effects. To achieve this, I am using the ng-style attribute within an ng-repeat attribute, and setting the ng-style ...

Tips for displaying animations only the first time using HTML and CSS:

Upon the initial visit to my website, a captivating animation introduces itself with the words "Hello. I'm Bob" as it gracefully fades into view. Navigating through the menu bar allows users to explore different sections of the site. However, there ...

Why is it important to understand the meaning of variable = [...variable] in Javascript ES6?

I need clarification on the following variable arg assignment arg = [...arg]; Can you explain what this code snippet does? ...

Following an ajax request, the tooltip feature in bootstrap fails to function properly

I am currently facing an issue with my files. I have an index.php file where I include another file named file1.php (which consists of all the necessary files for jQuery, js, etc.). Within file1.php, there is a table with buttons that trigger modals. The i ...

Unable to insert a CodeSandbox iframe within a Docusaurus document

Having trouble identifying the reason behind it, I managed to successfully embed a YouTube video iframe. However, when attempting to do the same with a CodeSandbox iframe, a build error keeps occurring preventing it from working. Could there be some limi ...