How can one transform an array (in the form of a JSON array) into a map?

After running my script, I receive an array (JSON Array) structured like this:

[{redirectCount=0, encodedBodySize=60962, unloadEventEnd=0, responseEnd=1601.699999999255, domainLookupEnd=995.7999999896856, ...

Now, I want to display the key-value pairs from the array similar to how I would do so with a Map:

Map<String, ?> map = cap.asMap();
for ( Map.Entry<String, ?> entry : map.entrySet()) 
{
    System.out.println(entry.getKey() + " value is " + entry.getValue());
}

I have attempted some resources online but haven't had any success yet:

  • How can i print json objects and array values?
  • How to Print JSON Array returned from controller class to jsp page
  • JSON - Iterate through JSONArray

I'm wondering if the JSON format that I am receiving is different from the standard formats?

The current code I am using for this task involves Selenium and Javascript to extract performance statistics:

String netData = ((JavascriptExecutor)driver).executeScript(scriptToExecute).toString();
System.out.println(netData);

The JavaDocs of executeScript() function specifies how various data types are handled when returning values:

  • For an HTML element, it returns a WebElement
  • For a decimal, a Double is returned
  • For a non-decimal number, a Long is returned
  • For a boolean, a Boolean is returned
  • In other cases, a String is returned.
  • For arrays, it returns a List with each object following specific rules. Nested lists are supported.
  • For maps, it returns a Map following the specified rules.
  • If the value is null or there is no return value, it returns null

Answer №1

If you're dealing with simple JSON data, one approach is to manually parse it...

Start by removing any { and [ characters:

jsontext = jsontext.replaceAll ("[\\[\\]{}]", "");

Then split the JSON array using a comma separator:

String[] items = jsontext.split(",");

Next, for each item, split it using the equals sign as a separator, and add it to your array:

Map<String, String> array;

for (String s: items){

    String[] item = s.split("=");
    if(item.length == 2){
        array.put(item[0].trim(), item[1].trim());
    }else{
        System.out.println("Error with: "+ s);
    }
}

If you want ? as your map array, you'll need to handle conversions from String to Int, etc...

For more complex JSON structures (nested arrays, etc), you may need to first resolve and store inner arrays before processing the outer ones.

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

Having trouble with getting the second JavaScript function to function properly?

I am facing an issue with the second JavaScript function. When I click the 'Send Mail' button, it should call the second function and pass it two values. However, the href line (second last line in the first function) is not rendering correctly. ...

Performing an HTTP request response in JavaScript

I am trying to make an HTTP request that returns the data in JSON format using 'JSON.stringify(data)'. var xhr = new XMLHttpRequest(); xhr.open("GET", "/api/hello", true); xhr.send(); xhr.onreadystatechange = function () { console.log(xhr.r ...

Obtaining a JSON file from Firebase Storage

Is it possible to retrieve a JSON file from Firebase Storage for use without needing to push it back? If so, how can I accomplish this using Angular with Firebase Storage? If not, would the Firebase database be a better option for this scenario? I have ...

Verification response parameter not received from Google Authentication Express

I've been working on implementing a "sign in with Google" feature for my localhost website. Despite receiving the POST request, I noticed that it lacks the credential parameter. I'm unsure if this issue lies within the code or the API configurati ...

Integrating a Vue application with an OpenId provider using the OpenId Connect library

Currently, I am in the process of developing a Single Page Application with Vue on the client-side and Java Spring REST APIs on the backend. My goal is to add security measures using OpenId Connect, specifically with RapidIdentity as the provider. Unlike ...

Dealing with CORS policy challenge

I am encountering an issue with Access to XMLHttpRequest at 'http://demo.equalinfotech.com/Iadiva/images/product/1634623781ladiva_barbara_01.glb' from origin 'http://localhost:8100' being blocked by CORS policy due to the absence of the ...

What could be causing my input box to act strangely when users attempt to input information?

I seem to be facing an unusual issue with the <input onChange={this.handleArticleId} value={this.props.articleIdValue} placeholder="article id"/> field. Whenever I try typing something, the letter only appears in the input box after clicking on the s ...

Steps for displaying only one collapse at a time using either Bootstrap 3 or Bootstrap 4

As I work on constructing a website from the ground up using Bootstrap 4, I have encountered a roadblock that may be simple for an experienced Bootstrap developer. While I was able to find a solution involving raw Javascript code to collapse one element at ...

Caution: The current version of the package has been deprecated and is no longer supported. It is advisable to update to the newest version available

While executing the npm install -g node-inspector command, I encountered an error message that prompts me to upgrade something. Unfortunately, I am unsure of what needs upgrading and how to do it. The complete error message I received is as follows: C:&b ...

Unable to Modify TextField Component in React

Is it possible to attach variables to TextField and have those variables deleted as a whole and not editable? Check out the Codesandbox example HERE code <CardContent> <Autocomplete value={values.variable} options={variables} ...

The use of "app.use("*") appears to be triggering the function repeatedly

app.use("*", topUsers) is being invoked multiple times. The function topUsers is called repeatedly. function topUsers(req, res, next){ console.log("req.url", req.url) findMostUsefullReviewsAggregate(6) .then(function(aggregationResult){ ...

Issue with Webpack failing to bundle a custom JavaScript file

Here is the structure of my directory: Root -dist -node_modules -src --assets --css --js --scss --index.js --template.html --vendor.js package-lock.json package.json postcss.config.js tailwind.config.js common.config.js development.config.js production.co ...

What is the best way to eliminate YouTube branding from a video embedded in a website?

I am currently utilizing an <iframe width="550" height="314" src="https://www.youtube.com/embed/vidid?modestbranding=1&amp;rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe> This setup removes the "YouTube" logo from the ...

Seeking assistance with my Java code that is experiencing intermittent crashes

Having recently started using Selenium and Java, I find myself with nearly 950 lines of code in a single java class. Unfortunately, when running this code, it crashes randomly. The issue is that sometimes it works fine, but other times it will crash unexpe ...

Prepare the XML information for storage in a MongoDB collection using Golang

Seeking a solution to process extensive xml files, format them, and then archive the data in a MongoDB collection. Which method is most efficient from the options below? Parse large xml files, format them, and store directly in the MongoDB collection. P ...

Error: It is not possible to access the 'map' property of an undefined value 0.1

I'm currently experimenting with React.js and I encountered an error that's giving me trouble. I can't seem to pinpoint the root cause of this issue. Shout out to everyone helping out with errors: TypeError: Cannot read property 'map ...

When integrating AngularJS $http with WordPress, the desired response may not always be achieved

I recently implemented a wp_localize_script for ajax in my WordPress project: wp_localize_script('cb_admin_js', 'cbAjax', array('ajax_url' => admin_url( 'admin-ajax.php' ))); As part of testing, I used an $http. ...

Is there a way for me to display the image name at the bottom before uploading it, and have a new div created every time I upload an image?

Is there a way to display the image name at the bottom and have it create a new div every time an image is uploaded? I would appreciate any help with this... <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstra ...

Efficiently communicating updates to clients after executing multiple HTTP requests simultaneously in RxJS

Objective: Execute multiple asynchronous HTTP requests simultaneously with RxJS and trigger a callback after each request is completed. For instance: fetchData() { Observable.forkJoin( this.http.get('/somethingOne.json').map((res:Re ...

Selenium webdriver is unable to locate the draggable web element, despite another user successfully doing so using the same code

I'm currently facing an issue with the drag and drop functionality in Selenium WebDriver. Despite using Java in Eclipse to write my test scripts, I am unable to locate the specific web element for dragging. Interestingly, a friend of mine is able to f ...