Tips for accessing nested JSON values using Selenium

Here is a JSON snippet to work with:

"ACCOUNT":  
    {
        "AmountDue": "$36,812.99",
        "OutstandingBalance": "$27,142.27",
        "StatementTotal": "$9,670.72",
        "StatementDate": "12/6/2018",
        "DueByDate": "12/23/2018",
        "AccountNumber": "5-029-5685-55"
    },

I am trying to extract the AmountDue value for verification purposes against portal data.

Initially, I attempted a direct approach,

String amountToValidate = jsonObj.ParseJson(billMeterJson, "AmountDue").toString();

However, it seems I need to access it from a multi-level structure. Any suggestions on how to achieve this? I tried this method but encountered an error:

String amountToValidate = jsonObj.ParseJson(billMeterJson, "data.ACCOUNT[0].AmountDue").toString();

Answer №1

Utilize the JsonPath feature from RestAssured as it is an excellent library for parsing JSON Objects and Arrays.

Include this Maven Dependency:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-path</artifactId>
    <version>3.3.0</version>
</dependency>

To parse JSON, provide the data as a String or File, then use JsonPath.from() method and pass the data as an argument.

Sample JSON Structure:

{
  "data": {
    "ACCOUNT": [
      {
        "AmountDue": "$36,812.99",
        "OutstandingBalance": "$27,142.27",
        "StatementTotal": "$9,670.72",
        "StatementDate": "12/6/2018",
        "DueByDate": "12/23/2018",
        "AccountNumber": "5-029-5685-55"
      },
      {
        "AmountDue": "$40,000.00",
        "OutstandingBalance": "$27,142.27",
        "StatementTotal": "$9,670.72",
        "StatementDate": "12/6/2018",
        "DueByDate": "12/23/2018",
        "AccountNumber": "5-029-5685-55"
      }
    ]
  }
}

Here's how you can implement it in code:

        JsonPath path = JsonPath.from("{\r\n" + 
                "  \"data\": {\r\n" + 
                "    \"ACCOUNT\": [\r\n" + 
                "      {\r\n" + 
                "        \"AmountDue\": \"$36,812.99\",\r\n" + 
                "        \"OutstandingBalance\": \"$27,142.27\",\r\n" + 
                "        \"StatementTotal\": \"$9,670.72\",\r\n" + 
                "        \"StatementDate\": \"12/6/2018\",\r\n" + 
                "        \"DueByDate\": \"12/23/2018\",\r\n" + 
                "        \"AccountNumber\": \"5-029-5685-55\"\r\n" + 
                "      },\r\n" + 
                "      {\r\n" + 
                "        \"AmountDue\": \"$40,000.00\",\r\n" + 
                "        \"OutstandingBalance\": \"$27,142.27\",\r\n" + 
                "        \"StatementTotal\": \"$9,670.72\",\r\n" + 
                "        \"StatementDate\": \"12/6/2018\",\r\n" + 
                "        \"DueByDate\": \"12/23/2018\",\r\n" + 
                "        \"AccountNumber\": \"5-029-5685-55\"\r\n" + 
                "      }\r\n" + 
                "    ]\r\n" + 
                "  }\r\n" + 
                "}");
        System.out.println(path.getString("data.ACCOUNT[1].AmountDue"));

Create a JsonPath instance using unparsed String data, followed by using path.getString() to extract the desired value. Adjust the index if you want to retrieve AmountDue from a different account.

The line

System.out.println(path.getString("data.ACCOUNT[1].AmountDue"));
will output $40,000.00

If changed to

System.out.println(path.getString("data.ACCOUNT[0].AmountDue"));
, it will print $36,812.99

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

The inputstream yields a null value which prevents the XML from being parsed

Trying to implement the worldweatheronline api for my app to fetch weather data. However, I'm facing an issue where the Inputstream "is" always returns null when I debug the code snippet below. The provided example code also has several log.d statemen ...

Difficulty activating JavaScript function - unsure of proper implementation

I'm having trouble with calling a function instead of an alert in my code. I tried using FunctionsName(); and removing the alert(''); but it doesn't seem to be working for me :( Could someone please take a look at the following code an ...

Select either the "Enabled" or "Disabled" option from the dropdown menu using Selenium webdrivers

Being new to web drivers, I am trying to select between enabled and disabled options from a dropdown menu. For example, let's say we have 2 options: https://i.sstatic.net/NCgeE.png 2.https://i.sstatic.net/W9OS2.png The scenario is as follows: I can ...

Angular2: Leveraging click events to manage CSS classes on elements

I am currently developing a web app using Angular 2. I'm facing an issue where the active element should receive an extra CSS class when clicked, but adding the ":active" CSS attribute with a custom class doesn't work as expected. The ":focus" pr ...

Python unittest raised an AssertionError stating that the Unicode string is not equivalent to another Unicode string

I have a web server that generates HTML code similar to the following: <div class="well"> <blockquote> <h2>Blueberry Pancakes Are Delicious</h2> </blockquote> </div> After writing a functional test, I e ...

json parsing - Retrieve specific values based on set criteria

I am currently working on extracting specific values from a JSON file. My goal is to retrieve the "generator" and "payload" values. The challenge here is that some items have multiple results, and some generators also have multiple items. In such cases, I ...

What is the best way to split this xpath into two sections with selenium in JAVA?

Original Xpath: (//div[@style='display: table-row;']//following-sibling::div)[38] I am attempting to break down the above xpath into two parts like so: //div[@style='display: table-row;'] & ./following-sibling::div[38]. The follow ...

The Chrome browser fails to execute code after using the Selenium WebDriver

from selenium import webdriver from selenium.webdriver.chrome.service import Service s = Service('/usr/bin/chromium-browser') driver = webdriver.Chrome(service=s) print("the driver is now active") After this code snippet runs, the out ...

Exploring Three.js raycasting in a non-full screen scenario

I've encountered some challenges with raycasting in three.js recently. The div element I'm using is not fullscreen, which I believe is causing issues with the raycast positioning that I'm struggling to resolve. let mouseVector = new THR ...

Displaying the preselected option in a Select dropdown menu using Angular

Here is the code snippet I have: <select label="people" id="ppl" [(ngModel)]="Selectedppl" (ngModelChange)="onPplSelection($event.target.value)"> <option>select people</option> <option *ngFor="let x of peopleList" [ngValue]="x"> ...

In what situations might a finally block fail to execute?

Are there any circumstances where the code in a finally block may not be reached, aside from the usual suspects like process exit(), termination signal, or hardware failures? In this TypeScript code snippet that usually runs smoothly in node.js, occasiona ...

Locate a particular word in every element within an array range (angularjs)

I'm just getting started with learning angularjs and I would appreciate some kindness as a beginner. Currently, I am working on creating a poll app using angular. In my project, I have an array scope named items, which holds all the items to be adde ...

Steps for triggering Docusign Clickwrap with a button press

My current project involves integrating docusign clickwrap codes. I want the clickwrap to appear when a user clicks a button. However, when I use the code below, the clickwrap opens directly. How can I trigger the ds-click using a button click event? For ...

Issue with triggering the change event for <select> tag

Whenever the selected value of the drop down changes, the following code does not work as expected. Please make corrections if any errors are present. <!doctype html> <html lang="en"> <head> <meta charset="utf-8</scri ...

Learn the steps to flashing images consecutively in sets of four on Android devices

Is it possible to create a blinking effect with up to 4 images appearing back to back? Essentially, I would like one image to be shown and then disappear, followed by the next image appearing in the sequence. This pattern should continue for my specific ...

Exploring the functionality of routes with the identifier :id

Is there a way to test routes with :id parameters included in them? Let's consider an example where we have a route like this: Router.get('/:id/profile I came across a scenario in someone else's code where they passed a string of numbers ...

Access the tapped region of an image on an Android device

Currently, I am developing a Quiz application that successfully displays normal questions in a TextView. I am now looking to incorporate images, such as identifying differences between two images or finding hidden letters within an image, where the user mu ...

Leveraging jQuery to extract the value from a concealed form field

Seeking assistance with a jQuery issue... I am attempting to use jQuery to retrieve the values of hidden fields in a form. The problem I am facing is that there are multiple forms displayed on the same page (result set items for updating), and the jQuery ...

AngularJS Skype URI Button Problem

Implementing a Skype button in my project using AngularJS has been challenging. Here is the code I am currently working with: HTML: <script type="text/javascript" src="http://www.skypeassets.com/i/scom/js/skype-uri.js"></script> <skype-ui ...

JavaScript threw an error because it encountered an unexpected or invalid token

I can't seem to identify the error in this code. Can someone please help me correct it? document.write(' <div> <a href=http://www.socialsignal.ir style=\'\\padding:5px;text-decoration: none;border: 1px solid #555;ba ...