How can values be extracted from a multi-dimensional array using JSON.parse()?

Here is a JSON array before using JSON.parse:

var temp = {
      "queries": [
    {
      "sample_size": 3,
      "results": [
        {
          "name": "temperature",
          "tags": {
            "Tag": [
              "temperature"
            ]
           },
           "values": [
            [
              1452221580000,
              27.5
            ],
            [
              1452221640000,
              27.1
            ],
            [
              1452221700000,
              27.3
            ]
           ]
        ]}
     ]}
    }

The goal is to extract a value from the array using JSON.parse().

var jsonparse_temp = JSON.parse(temp);
var dataNum = jsonparse_temp['queries'][0]['sample_size'];
var timestamp1 = jsonparse_temp['queries'][0]['results'][0]['values'][0][0];
var value1 = jsonparse_temp['queries'][0]['results'][0]['values'][0][1];

Next, we check if value1 equals 27.5. It's uncertain whether this method correctly assigns the value to the variable.

Answer №1

It is not a JSON string but rather a well-formed object that does not require parsing. With a nested array, the object element needs to be extracted from the array using the index.

var temp = {
  "queries": [{
    "sample_size": 3,
    "results": [{
      "name": "temperature",
      "tags": {
        "Tag": [
          "temperature"
        ]
      },
      "values": [
        [
          1452221580000,
          27.5
        ],
        [
          1452221640000,
          27.1
        ],
        [
          1452221700000,
          27.3
        ]
      ]
    }]
  }]

};

// Extracting values using bracket notation
var dataNum = temp['queries'][0]['sample_size'];
var timestamp1 = temp['queries'][0]['results'][0]['values'][0][0]
var value1 = temp['queries'][0]['results'][0]['values'][0][1];

console.log(dataNum, timestamp1, value1);

// Extracting values using dot notation
var dataNum1 = temp.queries[0].sample_size;
var timestamp11 = temp.queries[0].results[0].values[0][0]
var value11 = temp.queries[0].results[0].values[0][1];


console.log(dataNum1, timestamp11, value11);

Answer №2

A representation of a JSON array is displayed below:

This does not qualify as JSON; rather, it is a JavaScript object. JSON is not present in your query.

var jsonparse_temp = JSON.parse(temp);

The result will be undefined because temp does not contain a JSON string.

['queries']['sample_size'];

'queries' is an array, not an object, so it does not have a 'sample_size' property.

The initial value within that array is an object that indeed possesses the mentioned property.

You must navigate through each level of the data structure sequentially without skipping any levels.

var dataNum = temp.queries[0].sample_size;

Answer №3

Here is an updated version of your code:

let dataSample = temp['queries']['sample_size'];
let timestamp1 = temp['queries']['results']['value'][0][0];
let value1 = temp['queries']['results']['value'][0][1];

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

Struggling to forward POST Request using Express and EJS

I'm currently developing an application using Node.js, Express, and EJS. The goal is to have the app redirect users to a different page (for example, from localhost:3000/ to localhost:3000/about) upon clicking a button. Despite successfully receiving ...

Placing a dropdown menu on top of an image

I currently have a slightly rotated menu bar with two buttons as an example: https://i.stack.imgur.com/0sI2P.jpg Due to the rotation, normal HTML handling is not feasible. I am considering using a <map> element to create hyperlinks over the menu it ...

How to utilize DefinePlugin in Webpack to pass NODE_ENV value

I am attempting to incorporate the NODE_ENV value into my code utilizing webpack through the use of DefinePlugin. I have reviewed a similar inquiry on Stack Overflow, but I am still encountering issues. Here is the configuration I am working with: In pac ...

When attempting to navigate to a new route with a query, I encounter the error message "NavigationDuplicated: Avoided redundant navigation to current location."

I'm facing an issue with my navigation header setup. It includes a search bar that redirects users to the home view with the search query as a parameter. Here's the code snippet for reference: <template lang="html"> <div cl ...

Generate options for a dropdown menu based on the choice made in another dropdown menu utilizing ajax technology

Greetings, I am currently working on a JSP page that features a form with two drop-down lists. The first drop-down is designed to display the country names. While the second drop-down should show the states corresponding to the selected country. I have ...

Looking to introduce Vue.js into an established SSR website?

Can Vue be used to create components that can be instantiated onto custom tags rendered by a PHP application, similar to "custom elements light"? While mounting the Vue instance onto the page root element seems to work, it appears that Vue uses the entire ...

A stationary webpage nested within a lively pathway on NuxtJS

I have a Nuxt app with a list of cars available at: /cars. You can select a specific car at /cars/:id. I would like to have a toolbar that routes to different views such as: /cars/:id/routes, /cars/:id/drivers, etc. Within the /cars/:id page, I have creat ...

When a request body containing a non UTF-8 character is received, it results in a JSON parse error displaying the message: "Invalid UTF-8 start byte 0

Encountering an exception while trying to parse the JSON request body, The issue arises from a special character "®" (non UTF-8) in the request body, leading to parsing failure. How can one effectively handle non UTF-8 characters within the req ...

Creating messages from an array using vanilla JavaScript or jQuery

I have an array of objects containing messages that I want to display on my webpage, but I'm unsure how to approach it. [{"message":"dwd","user":"csac","date":"07.04.2021 20:46"}, {"mes ...

How do ptr[i] and *(ptr + i) differ from each other?

When working with a pointer to an array, I've always accessed the elements using an indexer like myPtr[i] = stuff. However, while reviewing the implementation of BitConverter, I noticed that elements were being accessed by using *(myPtr + i) = stuff. ...

Ways to extract all values following a specific character in a list or array

Suppose we have a list like this: data = ['O', 'O', 'B', 'I', 'I', 'B', 'I', 'O', 'B', 'I'] The goal is to extract every index after B (including B) until ...

Verify the visibility of the toggle, and eliminate the class if it is hidden

I have implemented two toggles in the code snippet below. I am trying to find a solution to determine if either search-open or nav-open are hidden, and if they are, then remove the no-scroll class from the body element. $(document).ready(function() { ...

Implement ajax functionality to update an object within a JSP page

On my JSP page, I have implemented an accordion list (utilizing Bootstrap 3) with text and a Delete button within each node. When the user clicks on the delete button, that specific list item is removed. To construct the accordion list, I bring in an Array ...

Customize React Hook Form version 7 by incorporating a unique input method for handling empty values

Introducing my custom Input component: export type InputProps = { error?: string } & InputHTMLAttributes<HTMLInputElement> export const Input: FunctionComponent<InputProps> = ({ error, ...props }) => ( <input {...props} /> ) ...

Storing HTML table data in a MySQL database will help you

Operating a website focused on financial planning where users can input various values and cell colors into an HTML table. It is crucial to uphold the integrity of these HTML tables. How can I store the complete HTML table (including values and colors) i ...

What is the best way to display an Error 404 page in a statically rendered client-side page using Next.js?

import { onAuthStateChanged } from "firebase/auth"; import Link from "next/link"; import { useRouter } from "next/router"; import { useEffect, useState } from "react"; import { auth } from "../../lib/firebase&qu ...

Iterate through the form fields and save the information into an object

I am attempting to create a JavaScript object by looping through form inputs. const data = {}; // loop through each input found in form $('#form_name').filter(':input').each(function() { const $id = $(this).attr('id'); c ...

Decoding JSON using Alamofire 4.request

Looking for some guidance on updating my old code that uses a Alamofire request: func downloadItemDetails (completed:DownloadComplete) { let url = _itemUrl! Alamofire.request(.GET, url).responseJSON { (request:NSURLRequest?, response:HTTPURLRespon ...

Looking to display a gif when a user clicks a button

I need help with making a spinner gif hidden in Unbounce and then show when the user clicks a button. The button is labeled #lp-pom-button-279 and the image is labeled #lp-pom-image-288 My attempts to use JS and CSS have resulted in the gif being either a ...

I am constantly reminded by React hooks to include all dependencies

Imagine I am using useEffect to pre-fetch data upon initial rendering: function myComponent(props) { const { fetchSomething } = props; ... ... useEffect(() => { fetchSomething(); }, []); ... ... } My linter is warni ...