Exploring Entries in Several JSON Arrays

In my current project, I have successfully generated JSON using JSON-Simple.

Query:

I am seeking guidance on how to extract specific elements like "Sentiment," "score," and "review" from this JSON array.

Although I have referred to a helpful resource here, I am still feeling a bit puzzled. Assistance would be highly appreciated. JSON Data:

{
    "Restaurant3": [
        {
            "sentiment": "positive",
            "score": "0.665205",
            "review": "Good Indian food in campbell that's better than average at a fair price. Will come back."
        }
    ],
    "Restaurant1": [
        {
            "sentiment": "positive",
            "score": "0.457413",
            "review": "People can say what they will about this being McIndians but I have ALWAYS had a solid meal at Tandoori Oven and was NEVER disappointed with the food.The saag lamb may be my favorite dish in the world as long as I can enjoy a cucumber salad and plenty of mint cilantro chutney to cool down my mouth. The vegetarian specials are also excellent every time. My only gripe is the menu can be a bit pricey and they have screwed around with student specials that used to get you two meals for under $10. ... Perhaps they realized it was too good of a deal?"
        }
    ],
    "Restaurant2": [
        {
            "sentiment": "positive",
            "score": "0.684585",
            "review": "We live near by and this is one of our favorite quick Indian food stop.I really like their butter chicken which is very creamy and fairly thick. The chicken inside is well spiced and grilled beforehand to give a good texture. Their baagen bharta is good as well, not as mashed up as other places and had a good mix of spice. Another thing to try is the tandoori salmon. It's juicy on the inside and crunchy on the outside. Do expect long lines during lunch, but dinner time it's fairly open."
        }
    ]
}

Using JSON-Simple Library to Generate the JSON Array:

 List  l1 = new LinkedList(); //LinkedList.
 List  l2 = new LinkedList();
 List  l3 = new LinkedList();
 JSONObject obj2 = new JSONObject(); //JSON-Simple Library
 obj2.put("Restaurant1", l1); //I'm making a linked list and passing them to make nested json
 obj2.put("Restaurant2", l2);
 obj2.put("Restaurant3", l3);
 String answer = obj2.toJSONString();
 System.out.println(answer); //prints JSON
 return answer; //Returning entire JSON (for now)

Answer №1

const jsonData = { ... }; // insert your JSON data here
const sentimentValue = jsonData.Restaurant3[0].sentiment;

When working with arrays in your JSON, remember to specify the index for the subelement

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

Conditionally submit a form using JQuery

I need to implement a validation condition using jQuery for a form submit button. The requirement is that the form should only be submitted if the user enters a valid email address. HTML code : <form method="post" action="{% url sportdub.views.login ...

When a mobile device is rotated, the screen on a jQuery application will automatically shrink

Having trouble with JQM and device rotation on iOS devices. The screen doesn't resize properly when rotated. I have this line in the header to handle display size: <meta name="viewport" content="height=device-height,width=device-width,initial-scal ...

Adjust the classes of the static navigation bar based on the background of the section it is positioned over

In the process of developing a website using Bootstrap 4, I encountered a challenge with sections featuring both light and dark backgrounds along with a fixed navbar. The navbar, which is set to dark using the css class bg-dark, becomes indistinguishable ...

Retrieve information using JavaScript and save it within a PostgreSQL Database table

I have received data from a device in HEX format as shown below: <Buffer 00 cc> My goal is to convert this into TEXT format and store the value in a PostgreSQL database. However, I am encountering an error message while trying to process it for dat ...

Design a background image that is optimized for both high-resolution retina displays and standard non-ret

Scenario I am working on a web page where I want the background image to be fixed, covering the entire screen or window (excluding tablets and smartphones). The background image has been created using ImageShack. Everything is running smoothly so far. T ...

Issue with IntersectionObserver not detecting intersection when the root element is specified

I am encountering an issue with my IntersectionObserver that is observing an img. It works perfectly when the root is set to null (viewport). However, as soon as I change the root element to another img, the observer fails to detect the intersection betwee ...

Is it possible to manage how many times a functional react component re-renders based on changes in its state?

For my practice e-commerce app, I have a functional component called "Shop" with two states: [products, setProducts] = useState([10ProductObjects]) and [cart, setCart] = useState([]) Upon the initial render, 10 products are loaded and each Product compone ...

Creating a bot that will only respond once when a user sends multiple photos simultaneously

I'm currently working on a Telegram bot using nodejs. I am utilizing the node-telegram-bot-api library and have implemented the on('photo') method to handle when a user sends a photo to my bot. However, I am facing an issue where if a user ...

Display a dynamic table using a JSON array in a React application

Looking to render the following jsonArray on a React page: [{ "machine1": [{ "Image": "mysql:latest", "Names": "mysql", "Status": "Restarting (1) 18 s ...

javascript design pattern - achieving unexpected outcome

In the code snippet provided, the variable a is turning out to be undefined. Are you expecting it to display the parameter value passed in the parent function? function test(a) { return function(a) { console.log('a is : ' + a); // Ou ...

Why aren't variables showing up on the right when using writeFileSync in Node.js?

I'm attempting to insert a variable as ${Y} but instead of getting the actual data in Y, my output is showing (how can I write variable ${Y}). Does anyone have a solution for this? const fs = require('fs'); const Y = fs.readFileSync('./ ...

"Experience the ease and efficiency of Shopify order processing

After looking at the Shopify documentation for fulfillment, I came across this example: POST /admin/orders/#{id}/fulfillments.json { "fulfillment": { "tracking_number": null, "line_items": [ { "id": 466157049 } ...

Utilize Vue in external files

One way I would like to improve readability in my project is by defining routes in an external file. The starting point for my Vue app is the main.js file, where I initialize everything. Take a look: import Vue from 'vue' import VueRouter from ...

Querying Parse Server for objectId information

Within my web app that utilizes the Parse Server Javascript SDK, I have implemented the following query. While the console log accurately displays the retrieved information, the objectId field appears as "undefined." var query = new Parse.Query("myClass") ...

"Unlocking the Power of jQuery: A Guide to Accessing XML Child

I'm struggling to extract the xml in its current format. While I can easily retrieve the InventoryResponse, I am facing difficulties when trying to access the child node a:Cost. Despite conducting research, I have been unable to find a solution that w ...

When the form is submitted, I am unable to record the checkbox value

Hi, I have a question regarding submitting a form to the "/delete" route when a checkbox is checked. Although I am able to submit the form successfully, I am facing an issue retrieving the checkbox value that I assigned using ejs. Below are the relevant co ...

Is it possible to store the output of every iteration in a Scenario Outline and combine all the responses into one JSON file for easy access?

https://i.sstatic.net/PRDI2.pngI am facing an issue with saving the json response of each iteration of the Scenario Outline and merging all responses into a single json file. Unfortunately, I have not been successful in saving it in the current feature f ...

Coordinating a series of maneuvers

When it comes to coordinating multiple sequential actions in Redux, I find it a bit confusing. I have an application with a summary panel on the left and a CRUD panel on the right. My goal is to have the app automatically update the summary after a CRUD op ...

What is the best way to implement window.load in React Native?

I'm encountering an issue with a simple button on my page in Expo/React Native. When I try to navigate to a new page using window.open upon clicking the button, I receive an error message saying "undefined is not a function." Although I am utilizing ...

How can I determine if a URL in react js includes a specific string?

I am working on a project where I need to check if a given URL contains the string youtube using react hooks in React JS. This is what my current code looks like: useEffect(() => { let srcLink = "www.google.com/https://img.youtube.com/vi/h9-qcy3HQn ...