JavaScript is a powerful tool for reading JSON files

I'm trying to figure out how to parse a nested object in JSON using JavaScript. Here's the code I have so far:

var myRequest = new Request('test.json');

fetch(myRequest)
  .then(function(response) { return response.json(); })
  .then(function(data) {
          console.log(data. ??????????);

  });

Here is the JSON file I am working with:

{
    "products": {
        "29033669": {
            "anzahl": "11x",
            "img": "https://static.openfoodfacts.org/images/products/29033669/front_de.3.400.jpg",
            "name": "Zitronenteegetränk"
        },
        "4001686386613": {
            "anzahl": "1x",
            "img": "https://static.openfoodfacts.org/images/products/400/168/638/6613/front_de.17.400.jpg",
            "name": "Haribo Saft Goldbären"
        },
        "4008400207322": {
            "anzahl": "5x",
            "img": "https://static.openfoodfacts.org/images/products/400/840/020/7322/front_de.6.400.jpg",
            "name": "Kinder Schokolade"
        },
        "40518152": {
            "anzahl": "4x",
            "img": "https://static.openfoodfacts.org/images/products/40518152/front_en.3.400.jpg",
            "name": "Karamalz classic"
        },
        "676478232": {
            "anzahl": "1x",
            "img": "https://cdn4.iconfinder.com/data/icons/aami-web-internet/64/aami18-38-512.png",
            "name": "Bananen"
        },
        "7613035499768": {
            "anzahl": "4x",
            "img": "https://static.openfoodfacts.org/images/products/761/303/549/9768/front_de.6.400.jpg",
            "name": "Choclait Chips Classic"
        }
    }
}

Any help on this would be greatly appreciated! Levi

Answer №1

To determine the data type, start by using console.log(typeof(data)). If it is a string, you can parse it into an object with const objData=JSON.parse(data). Then, you can access the products with data.products.

If the data is already in object form, simply access the products using data.products.

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

jQuery does not provide the reference of a basic canvas element

I'm having trouble with a simple initialization function that is supposed to create a canvas element in the body and save its reference in a variable. No matter what I try, jQuery doesn't seem to want to return the reference. I attempted refere ...

Learn how to extract the first occurrence of repeated data fields by parsing JSON using the org.JSON library in Java

I need help extracting the initial occurrence of "actualEPS" from this JSON file: {"symbol":"AAPL","earnings":[{"actualEPS":2.34,"consensusEPS":2.17,"estimatedEPS":2.17,"announceTime":"AMC","numberOfEstimates":10,"EPSSurpriseDollar":0.17,"EPSReportDate ...

The functionality of Jquery ceases to work once a setTimeout function is implemented

I need some help getting a series of functions to be delayed by 2 seconds using setTimeout. For some reason, whenever I try to implement this, the code stops executing altogether. I've double-checked the syntax and everything seems fine because it wor ...

Guide to leveraging dependency chaining in Node.js

Scenario: I am working with a node.js library that utilizes sequelize for defining and exporting models. This library is being used in my backend application, which also requires access to the functionalities provided by sequelize. Query: How can I proper ...

Trouble with $.getJSON while trying to obtain song tempo data with getSongBPM

Still learning the ropes, so bear with me. I am trying to retrieve the BPM of a song using the getSongBPM public API. However, I'm not seeing any data in the console. // Please note that the API key has been updated $.getJSON("https://api.getsongbp ...

Newly included JavaScript file displays on view page, but triggers a 404 error when attempting to open

Once I implemented the following code in the child theme's function.php file: add_action('wp_enqueue_scripts', 'js_files'); function js_files() { wp_register_script('ajax_call_mkto', get_template_directory_uri() . ' ...

Tips for producing/reserving cropped images from a photo? (includes converting images to base64 format)

Imagine having two square datasets taggedImages: { 0: {id:0, left:100, top:100, thumbSize:100, type: 'A', seasons: ['All', 'All']}, 1: {id:1, left:200, top:200, thumbSize:100, type: 'B', seasons: ['All&apo ...

Verify Radio Buttons in AngularJS

I thought validating a selection from a radio group would be simple, but I'm struggling to find the right solution. In my form, I need to ensure that at least one option is selected from the radio buttons. Using the 'required' attribute on e ...

"Error encountered when making a request to Google API using Ember.js, response remains

Trying to fetch place suggestions from Google API using Ember js. Below is the code snippet for the service module: fetch(){ let url=`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=IL&types=geocode&key=API_KEY` return Ember.RSV ...

Tips for creating a fixed footer that adjusts with a flexible wrapper

Feeling incredibly stressed, I embarked on a quest to find the perfect sticky footer. After searching Google for what seemed like an eternity, I came across multiple tutorials recommending the use of min-height:100%. However, this approach caused the wrap ...

Utilizing JQuery to differentiate a single element within a group of elements

As a beginner in the world of jquery, I am attempting to assign a font awesome icon star (fa-star) to differentiate between admins and regular members within the group members bar. The usernames have been blurred out for privacy reasons, but my goal is to ...

Identify the element in the array that corresponds to the current route

Within an array, I have various routes such as: /app/manual/:id /app/manuals/:id /app/feedback ... In my react.js application, I am looking to compare the location.pathname with the paths in my array and retrieve the title associated with the matching pa ...

In search of inspiration to create a recipient list similar to Gmail using Vue3?

Recently, I've been trying to create a recipient list similar to that in Gmail using Vue3 but I'm stuck and unable to find helpful resources online. recipient list I have an array of email addresses that I can loop through and display in a div. ...

Ways to address conflicting getter definitions for a property in Jackson when the source code is not accessible

Encountering an issue that states: HTTP Status 500 - Could not write JSON: Conflicting getter definitions for property "oid" The root cause is the presence of two similar methods in the class: getOID (deprecated) and getOid Unfortunately, modi ...

Using JavaScript to define an array of objects

My issue lies with transforming a JSON structure like the one below: [{ "groupid": 29, "percentage": 14 }, { "groupid": 29, "percentage": 22 }, { "groupid": 59, "percentage": 66, }] I am looking to convert it into the format shown ...

Choose a numeric value and then adjust it to display with exactly two decimal places

My goal is to create a code that achieves the following tasks: Add an ID to every nth child Round the number in each nth child to 2 decimal places Prefix the numbers with a pound sign (£) Loop through until all the nth children in a table are processed ...

No data received from XMLHttpRequest

Within my Java Web application, I'm making an ajax request using the following code: <script type="text/javascript"> function selectTableHandler() { console.log("inside selectTableHandler"); var xhttp = new XMLHttpRequest(); var se ...

Dynamic Dropdown Selections with AJAX

After exploring various resources, I found a solution for creating a multiple drop-down menu on this site: Roshan's Blog The implementation is mostly successful, except for an issue with the third drop-down box. (Dropdown1: Clients, Dropdown2: Loca ...

The Ajax request returned a status of 200, yet an error message was displayed

Even though the status is 200, why does it print the error message inside alert("error...");? function makeSelect() { var blouseoption = document.querySelector('input[name="blouseoption"]:checked').value; var url = "http://dukano.co/sakh ...

Creating a circle in SVG that cannot be scaled using Javascript

I'm working on a map project using JavaScript and SVG for drawing the lines. One feature I'd like to implement is the ability to search for a specific road, and if found, display a circle on the map. I understand how to draw a circle in SVG, bu ...