Leveraging JsonPath to retrieve data without prior knowledge of the key

I have a Json string that looks like the following:

  "files": {
     "fileA.c": {
         "size": 100
     },
     "fileB.txt": {
         "size": 200
     }
  }

My goal is to extract the names of the files, {"fileA.c","fileB.txt"}, using JsonPath. It's important to note that the number of files is unknown.

The issue I'm facing is not knowing whether the file name is a key or a value:

  • If it's a key...I have no way of knowing the key name since that's precisely the information I'm trying to extract.
  • If it's a value, then what exactly is its corresponding key?
  • Is it possible to use JsonPath to retrieve the file names? If yes, how can it be done?
  • In case JsonPath is unable to accomplish this task, is there another Java library for handling Json data that could help achieve the desired outcome?

Answer №1

When looking at the scenario you provided, fileA.c and fileB.txt serve as keys that can be accessed through iteration on the enclosing object's key "files".

In this particular situation, JSONPath may not be the most suitable (or applicable) method to use since it is intended for accessing elements when the document structure is known, meaning that the keys are already familiar. Utilizing a JSON parser would likely be a more straightforward approach.

Answer №2

If you're looking to improve your data structure, consider organizing it in the following way:

var filesData = {
   "files": [
      {
         "name": "fileA.c",
         "size": 100
      },
      {
         "name": "fileB.txt",
         "size": 200
      },
      {
         "name": "fileC.txt",
         "size": 50
      }
   ]
};

By structuring your data like this, you can take advantage of DefiantJS () to search for files with sizes larger than 100 as demonstrated below:

JSON.search(filesData, '//*[size >= 100]/name')

DefiantJS enhances JSON functionality by adding the "search" method, allowing you to query JSON structures using XPath expressions.

For a live demonstration using your specific data, feel free to check out this fiddle: http://jsfiddle.net/jRN22/

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 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 ...

What could be causing my post request to function properly in POSTMAN but not in my React application?

Here are my POSTMAN headers along with the settings I used to send my POST. It only started working when I switched the Content-Type to application/json. https://i.stack.imgur.com/Xz2As.png https://i.stack.imgur.com/aJtbD.png This pertains to the server ...

Can Node.js handle parsing this as JSON?

Attempting to parse a small API that returns somewhat invalid JSON. Trying the following approach: var request = require('request'), url = 'urlhere'; request({ url: url }, function(error, response, body) { ...

Having trouble generating package.json with npm init on my Mac

Every time I attempt to generate a package.json file by using the command npm init, I encounter the following issue: npm http GET https://registry.npmjs.org/init npm http 304 https://registry.npmjs.org/init npm http GET https://registry.npmjs.org/daemon n ...

What is the process of downloading dependencies with the command 'npm install'?

Upon navigating to the folder containing my package.json file for an Angular app, I noticed that when I run the command npm install, it takes a considerable amount of time (around 10 minutes) to download just 6 dependencies. After completion, it download ...

A node is receiving a JSON object through an axios POST request

I am working on a project where I have two unique URLs. The first URL receives a form action from an HTML page along with data and then makes a post request to the second URL. The second URL, in turn, receives a JSON and uses Express to make a GET request ...

Converting hexadecimal string to a double value in Java

Currently, I am working on decoding the value of the "Well-known Binary" format using Java. The Node script below accomplishes this task: Buffer.from('A4C0A7DEBFC657C0', 'hex').readDoubleLE() // returns -95.1054608 I am struggling to f ...

What is the best way to iterate through JavaScript objects within a Jade template?

Technologies such as Node.js, Jade, socket.io, jQuery, and JSON are being used in my project. In my "index.jade" file, I have the following code that receives "results" data as JSON from the backend: extends layout block content ul // more jade html h ...

Guide to forming an array by extracting specific properties from a nested JSON array using javascript

Currently, I have this list: list = { id: 1, arr: [ {index : 1 , description: "lol" , author: "Arthur"}, {index : 2 , description: "sdadsa" , author: "Bob"}, {index : 3 , desc ...

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 ...

Mapping JSON data from an array with multiple properties

Here is a JSON object that I have: obj = { "api": "1.0.0", "info": { "title": "Events", "version": "v1", "description": "Set of events" }, "topics": { "cust.created.v1": { "subscribe": { ...

Unable to retrieve JSON data from converting TXT using JavaScript, resulting in undefined output

After converting txt to JSON, I encountered an issue. const txt = JSON.stringify(`{ ErrorList: [{ 80: 'Prepared' }], Reference: [ { 'Rule Name': 'Missing 3', 'Rule ID': 1, 'Rule Des& ...

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 ...

The compilation of debug Java with Javac in CordovaLib is not being done incrementally

I am currently in the process of setting up Ionic on my new computer, but I have encountered an issue while trying to build a Cordova Android project that I can't seem to resolve. The software and versions I am using include: NodeJS v6.9.1 npm ...

How can we access a value within a deeply nested JSON object in Node.js when the key values in between are not

In the nested configuration object provided below, I am seeking to retrieve the value associated with key1, which in this case is "value1". It's important to note that while key1 remains static, the values for randomGeneratedNumber and randomGenerated ...

A guide on ensuring all necessary keys are present in a JSON document using Node.js

I have been researching various methods for efficiently checking if a key exists in a JSON file. The challenge I am facing is related to optimizing this process. My current workflow involves users uploading a CSV file which I then convert into JSON format ...

What exactly constitutes a circular data structure within JSON?

I'm encountering an issue in my Express app where I am receiving the following error: UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON Despite searching for similar problems, I am struggling to grasp the concept o ...

Utilizing JSON Data with Angular

Currently, I am in the process of developing an AngularJS client that communicates with a REST API running on NodeJS. To retrieve data, I make GET requests by accessing specific URLs with stock symbols appended, such as localhost:8080/stocks/aapl for Apple ...

"Exploring the dynamic capabilities of Node.JS and Java Publisher/Subscriber

I am working on developing an application where communication will be facilitated through a node.js server. This node server is responsible for receiving messages from other peers. Here is the code snippet for my node.js: var zmq = require('zmq&apos ...

Extracting data from a JSON object

Currently, I am facing an issue with my node.js code that is not working as expected when trying to fetch a value from a 3rd party website in JSON format. Although my code works fine for similar cases, it is failing to extract the price of a specific item ...