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

What is the best way to invoke a function from one controller in angularjs to another controller?

I am trying to implement a solution where I need to call the Listing function of testController from userController. I have placed a marker (//) in the code snippet below to indicate where I want to make this function call. This implementation is being d ...

Unable to access the property '__reactAutoBindMap' as it is undefined

I've been struggling with setting up server side rendering with React for the past week. It's a new project using an express server and I'm trying to render a simple hello world react app that utilizes react-router-component. To get some he ...

Guide to setting up Date Range Validator within MVC 4

Is there a way to limit the user from inputting a date outside of a specific range in my MVC 4 application? I'd appreciate any advice on how to achieve this. ...

Tips for stopping Vue.js automatic merging of CSS classes

Recently, I embarked on my journey with Vue.js and have been thoroughly enjoying the experience. However, I've stumbled upon a challenge that has me stumped. Despite searching high and low and studying the documentation, I haven't found a solutio ...

Tips for clearing a saved password in a browser using Angular.js and Javascript

There is an issue with the password and username fields in my Angular.js login page. When a user clicks on the 'remember me' option in their browser after logging in, the saved username and password are automatically displayed in the respective f ...

Leveraging data schemas to manage the feedback from APIs

I am curious about the benefits of modeling the API response on the client side. Specifically: First scenario: const [formData, setFormData] = useState(null); ... useEffect(() => { const callback = async () => { try { const fetchDa ...

Strange issue encountered when utilizing Worklight along with XSL transformation on a JSON response

I'm facing an unusual issue that I can't seem to resolve. Here is an example of a JSON response that I am dealing with. "values": [ { "time": "2014-02-26T09:01:00+01:00", "data": [ "A", "B" ] }, // additional objec ...

When using express, encountering a "Cannot GET / on page refresh" error

Currently working on a small MERN stack project. Managed to deploy it on Vercel successfully and the application runs as expected. Navigating to "/classes" and "/students" using the buttons in the browser works fine, however, upon reloading those pages I e ...

There seems to be an issue with Node.js/Express: the page at /

Recently, I've been working on some code (specifically in app.js on the server). console.log("Server started. If you're reading this then your computer is still alive."); //Just a test command to ensure everything is functioning correctly. var ...

Utilizing RxHttpClient in Micronaut to send a JSON body in a POST

Is there a way to send a POST request in Micronaut with a JSON body? The execute method shown below raises this question and the challenge of passing JSON data for it to function properly. HttpRequest<String> httpRequest = new SimpleHttp ...

Is there a more efficient method to select all the rows containing '1's in a specific cell within a large range of data?

As a beginner, I've developed a script that scans through a large table and extracts rows containing the value '1'. The table consists of approximately 2000 rows, so it's taking quite some time to process all of them. Is there a more e ...

Utilizing React and Material-UI to create an autocomplete feature for words within sentences that are not the first word

Looking to enable hashtag autocomplete on my webapp, where typing #h would display a menu with options like #hello, #hope, etc. Since I'm using material-ui extensively within the app, it would be convenient to utilize the autocomplete component for th ...

Having trouble accessing properties of an undefined object when trying to read 'credentials' in Firebase Auth within ReactJS

I need to verify the user's password again before allowing them to change it. Currently, my Firebase Auth setup is defined in Firebase.js and exported correctly //appConfig = ...(all the configurations here) const app = firebase.initializeApp(appConf ...

How to Dynamically Update Sass Styles with Webpack 2?

Currently, I am in the process of setting up a React application that utilizes Webpack2, webpack-dev-middleware, and HMR for the development phase. One peculiar issue that I have encountered is related to updating .scss files. When I make changes to my .sc ...

Ensuring that a service is completely initialized before Angular injects it into the system

When Angular starts, my service fetches documents and stores them in a Map<string, Document>. I use the HttpClient to retrieve these documents. Is there a way to postpone the creation of the service until all the documents have been fetched? In ot ...

What are the steps to successfully install OpenCV (javascript edition) on Internet Explorer 11?

I'm currently experiencing issues with getting the OpenCV javascript version to function properly on IE11 for contour detection. While my code runs smoothly on all other up-to-date browsers, I am encountering errors such as: TypeError: Object doesn&a ...

Show a specific div using jQuery fadeIn() when the user reaches the top of an HTML section

The code below has a specific purpose: 1) Determine the current scroll position. 2) Locate the parent article and determine its offsetTop for each .popup_next which represents a section on the site. 3) Calculate an offset value by adding 30px to the off ...

Choose the offspring of an element using jQuery

Currently, I have a function set up to open a modal dialog and populate it with information from the 'dblclicked' node: $(function(){ $(".delete").live('dblclick', function () { var id = $(this).attr('id'); ...

The steps to triggering a button click after e.preventDefault()

When attempting to prevent a click() event of a button by using preventDefault() after unbinding the button with unbind(), I encountered an issue where it did not work as expected. <script> $("#update2FAButton").on("click",function(e){ e.pre ...

Verify the functionality of a specific method invoked within another method through unit testing

I currently have a method in my Angular application that is triggered upon clicking. Inside this method, I pass a value to another private method. .ts file public onViewItem(item: Results): void { const ids = [item.data['id']]; this.anot ...