Navigating JSON Data in Groovy Using a Loop: A Handy Guide

Just starting out with Groovy and attempting to mock a service in SoapUI.

The task at hand involves loading a text file containing JSON data, and then matching that data to a specific node.

Here is what I have attempted so far:

def inputFile = new File("D:\\Users\\json.txt")
def InputJSON = new JsonSlurper().parseText(inputFile.text)

    InputJSON.each{  
        def ID1 = it
        it.items.each { 
            if(it.Number == itemNumber) 
            {
                log.info it
                requestContext.Id = ID1
            } 
        }
    }

While this works well, there is one problem – the format gets lost when ID1 loads into requestContext.Id from the file.

What I am aiming for is:

{
 "items" {
        "number" : 1475175072691
      }
}

However, what I end up getting is:

{
 metadata = {
        timestamp = 1475175072691
}
}

I'm puzzled as to why the double quotes " and colon : are stripped from my JSON. Any suggestions on how to resolve this?

Answer №1

Check out the code snippet below:

import groovy.json.*

def str = '''\
[
   {
      "items":{
         "number":1475175072691
      }
   },
   {
      "items":{
         "number":1475175072691
      }
   },
   {
      "items":{
         "number":1475175072691
      }
   },
   {
      "items":{
         "number":1475175072691
      }
   }
]'''

def json = new JsonSlurper().parseText(str)

json.each { 
  println JsonOutput.prettyPrint(JsonOutput.toJson(it))
}

The output displayed will be as follows:

{
    "items": {
        "number": 1475175072691
    }
}
{
    "items": {
        "number": 1475175072691
    }
}
{
    "items": {
        "number": 1475175072691
    }
}
{
    "items": {
        "number": 1475175072691
    }
}

To achieve this desired format, you must serialize and pretty print the json nodes accordingly.

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

Sentry: Easily upload source maps from a nested directory structure

I am currently developing a NextJs/ReactJs application using Typescript and I am facing an issue with uploading sourcemaps to Sentry artefacts. Unlike traditional builds, the output folder structure of this app mirrors the NextJs pages structure, creating ...

What is the best way to display images one by one from a map using a random fade effect?

I am in the process of creating a logo wall for a website. I successfully managed to display them randomly using a map, but now I want to make them appear one by one in a random order (for example: image 1, image 6, image 3, ...) and keep them visible once ...

Only the initial submission is allowed when submitting forms using jQuery $.ajax

Encountering an issue with submitting AJAX forms after following this particular tutorial. The forms are contained within div#upform and upon attempting to submit any of them using $.ajax, only the first one is being submitted. The code snippet in questio ...

Is there a way to invoke an Angular2 function from within a Google Map infowindow?

I am currently working on integrating Google Maps using javascript in a project, and I'm facing a challenge. I want to call an Angular2 function inside an infowindow as shown in the code snippet below. Pay attention to the infoContent variable that co ...

Modify the onerror function of the image tag within the onerror function

Here is a way to display images using the img tag: If 1.jpg exists, show 1.jpg. If not, check for 2.jpg and display it if it exists. If neither 1.jpg nor 2.jpg exist, display 3.jpg. <img src="1.jpg" onerror="this.src='2.jpg'; this.oner ...

Listen for the 'open' event on a node HTTP server

This question pertains to a previous inquiry I had about node httpServer encountering the EADDRINUSE error and moving to the next available port. Currently, my code looks like this: var port = 8000; HTTPserver .listen(port, function() { console.lo ...

Ways to display all current users on a single page within an application

I have come across a project requirement where I need to display the number of active users on each page. I am considering various approaches but unsure of the best practice in these scenarios. Here are a few options I am considering: 1. Using SignalR 2. ...

Iterate over a list of strings and convert them into key-value pairs in JSON format using Python

My CSV file looks like this: devid,1, devType,"type-928" devid,2, devType,"type-930" etc. The length of the lines may vary depending on the number of key-value pairs included. However, they must contain 'devid' and 'devT ...

Using Javascript within a PHP file to generate JSON output

Can you integrate Javascript code within a PHP file that utilizes header('Content-Type: application/json'); to produce output in JSON format? UPDATE: I'm attempting to modify the color of a CSS class when $est = 'Crest', but the J ...

Encountering a problem while deserializing a JSON response from Stripe

My attempt to deserialize the Stripe JSON response is mostly successful, but I encountered an error in some cases: Cannot convert null to a value type. Even though there seems to be a type present at the end. Here is the response: { "id": "evt_1Dez ...

Securing Your Content - Preventing Users from Right-Clicking and Using F12 on Your Website

I am looking to disable the Right-Click function on my website or display an error message saying "Protected Content!" when someone tries to right-click. I want to prevent others from viewing my Source Code. Although I know how to disable Right-Click, I am ...

Sorting arrays can yield varying results depending on the browser being used

The variations in output between Chrome 70.0, Chrome 69.0, and Firefox 63.0 for the same code are puzzling. var arr = [1,2,43,1233,5546,33,6,11]; arr.sort(() => -1); //[11, 6, 33, 5546, 1233, 43, 2, 1] arr.sort(() => 1); //[1, 2, 43, 1233, 5546, 33, ...

The <br/> tag is not functioning properly when retrieving text from a MySQL query

Currently, I am involved in a project that involves an A.I pushing text onto a MySQL database. Our goal is to display the ongoing writing process on a webpage. We are still actively working on this. We are retrieving the data and regularly checking the da ...

What location is most ideal for incorporating JavaScript/Ajax within a document?

Sorry for the seemingly simple question, but I would appreciate some clarification from the experts. When it comes to the three options of placing JavaScript - head, $(document).ready, or body, which would be the optimal location for ajax that heavily rel ...

Angular JS failing to display error messages

I'm experiencing difficulties displaying login validation errors with the following code. After clicking on the Login button, it redirects to the next page without showing error messages as expected. Any suggestions? index.html:- <!DOCTYPE ht ...

What is the best method for obtaining a JSON string from a URL?

The link to access the data is: {%22svc%22:%22avl_evts%22,%22app%22:%22hst%22,%22sid%22:%22e93c3c3fbc1e3add3a518ca9d3f28d65%22} The given URL contains a JSON string with various parameters and values. { "tm": 1395378731, "events": [ { "i": 82 ...

Troubleshooting Problem with ListItem Alignment in Material UI v0 involving Custom Avatar Component

Material UI version: v0.20.0 I'm facing an issue with aligning the leftAvatar value using the CustomAvatar component, as shown in the attached screenshot. Any assistance would be appreciated. CustomAvatar: The functionality of this component is cond ...

The 'userEvent.type' function in React Testing Library is failing to update the input value in a Material UI TextField component that has

I am currently facing an issue with a material UI TextField element that is meant to track the latitude value. The requirement is for the latitude to fall within the range of -90 to 90 degrees. I have implemented a unit test as a validation measure, howeve ...

What is the correct way to format responses written within response.write() in NodeJS?

Just starting out with NodeJS and express and following a tutorial on displaying two headings in the browser. Came across an issue where using res.send() twice wasn't working, so my instructor introduced me to the write method. Interestingly, when she ...

How can I export an ES Object in Node.JS to an NPM package?

I am currently facing a challenge involving an ES5 object/function that I want to integrate into an NPM package. This particular object is within a namespace defined as MY_NAMESPACE.myObject = function(){...} where MY_NAMESPACE is simply an object. Typic ...