Exploring the Depths: A Guide to Selecting Nodes in Java Based on Depth

In my current JSON representation, I have the following structure:

{
  "total": "555",
  "offset": "555",
  "hasMore": "false",
  "results": [
    {
      "associations": {
        "workflowIds": [],
        "companyIds": [],
        "ownerIds": [],
        "child": {
         "name" : "association1",
          "key" : "a1"
        }, 
        "quoteIds": [],
        "contentIds": [],
        "dealIds": [],
        "contactIds": [
          4646915
        ],
        "ticketIds": []
      },
      "scheduledTasks": [
        {
          "taskType": "REMINDER",
          "portalId": 214129,
          "engagementType": "TASK",
          "engagementId": 6604524566,     
          "timestamp": 1586815200000
        }
      ]
    },
    ...
]
}

To extract filtered information based on specified node selector string (similar to SQL), I am implementing the following code:

ObjectMapper objectMapper = new ObjectMapper();
JsonNode root = objectMapper.readTree(new File("/Users/pra/automation/foo.json"));
String result = root.at("/results/0/associations/0/child").toString();
Assert.assertNotNull(result);

The above code successfully filters the first nodes from the array using the 0 index. However, to obtain output for all matching elements, I attempted to use an asterisk (*) instead of 0 but encountered issues.

My attempt that failed looks like this:

String result = root.at("/results/*/associations/*/child").toString();

Desired Output:

[
{
   "name" : "association1",
   "key" : "a1"
},
...
]

I am open to exploring other Java-based alternatives to achieve this desired outcome. Thank you.

Answer №1

If you decide to make the switch to the Gson library, consider utilizing the im.wilk.vor:Voritem library available on GitHub or in Maven repository.

VorItem vorItemFactory = VorItemFactoryBuilder.standard.build();
JsonElement je = JsonParser.parse(...)

VorItem vi = vorItemFactory.from(je);
VorItem result = vorItemFactory.empty();

for (int idx = 0; idx < vi.get("result").list().size(); idx++) {
    result.get(idx).set("name", vi.get("result").get(idx).get("associations/child/name");
    result.get(idx).set("key", vi.get("result").get(idx).get("associations/child/key");

}

return result.asJsonElement().toString();

Answer №2

After implementing Andreas' recommendation, I found it to be incredibly efficient and user-friendly. Thanks to the JSONPath library, I was able to easily achieve the desired results.

The code snippet for implementation is shown below:

ObjectMapper objectMapper = new ObjectMapper();
String root = objectMapper.readTree(new File("/Users/janedoe/automation/data.json")).toString();
List<Object> associations = JsonPath.read(root, "$.results[*].associations.child");

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

ExpressJs res.json throwing error - Headers cannot be set after they have already been sent

In my current project using ExpressJS, I have a specific route set up like this: router.route('/monitor') .all(function (req, res, next) { next(); }).get(monitor.monitorServers); There is also a controller named 'monitor' which co ...

The compatibility between Node.js and Git seems to be lacking

I'm attempting to set up automatic deployment with GitHub. I have created a JavaScript file to act as a "server" to receive the hook from GitHub, and that part is working flawlessly. However, I'm struggling with getting my hook.sh script to execu ...

Retrieve a list of applications in JSON format from your Heroku account

Building a Node/Express app to showcase my portfolio. I found an interesting CLI command that allows me to view a JSON list of my apps and their properties directly in the terminal: https://devcenter.heroku.com/articles/using-the-cli#app-commands Now, I& ...

Does the compression ratio for GZip change depending on the library used, such as Zlib in NodeJS and SharpZipLib in .Net?

Context: I am currently conducting tests on the compression ratio of our device. The data from the device is transmitted in the form of Json payloads, specifically in JArray format. I will be measuring the size of this data in Bytes before it undergoes com ...

Array of JSON data passed in the request body

Recently, I have been attempting to pass JSON data to my req.body. The data structure is as follows: answers = ["A","B"]; //An array to be included in the JSON Object var Student_Answers = { //JSON object definition Answers: answers, matricNumber: ...

Retrieve a JSON response from within a schema housed in MongoDB

I have a document structure that looks like this: { "id": "someString", "servers": [ { "name": "ServerName", "bases": [ { "name": "Base 1", "status": true }, { "name": "Base 2", ...

Having trouble accessing JSON file again: "Encountered unexpected end of input error"

I have set up a cron-based scheduler to periodically retrieve JSON data from an external API every 2 minutes. The process involves writing the data to a file, reading it, cleaning it, and then storing it in a MongoDB collection. Everything works smoothly o ...

What is the best way to eliminate or substitute Unicode Characters in Node.js 16?

Currently, I have a file that is being read into a JSON Object. { "city": "Delicias", "address": "FRANCISCO DOMÍN\u0002GUEZ 9" } We are using this address to send it to the Google Maps API in order to ...

Managing package versions with package.json and teamcity integration

Our team utilizes TeamCity for builds and deployments. One of our goals is to have TeamCity automatically set the version number in the package.json file. In the past, we used a tool called gulp-bump to update the version number, but TeamCity's build ...

Understanding JSON Parsing in Jade

I am facing a challenge with handling a large array of objects that I am passing through express into a Jade template. The structure of the data looks similar to this: [{ big object }, { big object }, { big object }, ...] To pass it into the Jade templat ...

Tips on storing JSON array data in mongoose via req.body?

I've been struggling with this issue for some time now. After successfully using JSON and req.body to save data to my MongoDB database in Postman, I decided to work with arrays for the first time. However, I'm encountering difficulties. (Just t ...

Transmit information to the client-side webpage using Node.js

One of the main reasons I am diving into learning Node.js is because I am intrigued by the concept of having the server send data to the client without the need for constant querying from the client side. While it seems achievable with IM web services, my ...

What is the best way to retrieve my data/json from req.body in Express?

Recently, I started working with node.js and encountered an issue while trying to access JSON data on my node.js server through a post request. The goal is to send this data to an API and then pass it back to my front-end JavaScript file. Despite being abl ...

Creating a node server that will intercept all requests from an Angular frontend (using http) and route them to a

Currently, I am utilizing express on node for routing and incorporating Angular as the front-end framework. Additionally, Redis is being used for session management. My objective is to ensure that whenever an HTTP request is made from Angular, it first goe ...

Using Node.js to return JSON data containing base64 encoded images

In my database, I store all images as base64 with additional data (creation date, likes, owner, etc). I would like to create a /pictures GET endpoint that returns a JSON object containing the image data, for example: Image Data [{ "creation": 1479567 ...

Utilize Mongoose to seamlessly integrate online shopping cart items into MongoDB

I am facing an issue while trying to insert a shopping cart of items in the form of a JSON object into a MongoDB collection using a mongoose schema. Although the customer's ID is successfully stored (extracted from the User DB), unfortunately, the ca ...

Tips for speeding up the loading of JSON with large data on HTTP requests or webpages

When requesting the page (via HTTP or webpage), it seems to be very slow and even crashes unless I load my JSON data with fewer entries. This issue is critical as I anticipate needing to work with large amounts of data frequently in the future. Below are t ...

I am experiencing issues with the button click functionality in my Google extension

Greetings! I am currently developing a Chrome extension that will automatically redirect to my website and fill in the password. However, I am facing an issue with submitting the button click event. // Here is my manifest.json code { "name": "z", "v ...

An error occurred stating: "The require function is not defined in AngularJS and nodeJS."

I have searched through various similar questions here on SO, but none seem to provide a solution that fits my specific case. I am relatively new to using angularjs and nodejs, and I am encountering an issue that has me stuck. My goal is to save the input ...

Troubleshooting issues with the delete functionality in a NodeJS CRUD API

I've been struggling to implement the Delete functionality in my nodejs CRUD API for the past couple of days, but I just can't seem to get it right. As I'm still learning, there might be a small detail that I'm overlooking causing this ...