Access information from JSON file

Looking to extract data from an external JSON file and store it in a JavaScript array for manipulation?

Here is a snippet of the JSON file for reference:

"Country":[
      {
         "Country_Name":"India",
         "Country_Details":[
            {
               "State_Name":"TamilNadu",
               "Capital":"Chennai",
               .................
               ................
            },
            {
               "State_Name":"Kerla",
               "Capital":"Trivandram",
               ................
               ................
            }
         ]
      },
      {
         "Country_Name":.......,
         "Country_Details":[
            {
              ...........
              .........
              .........
              .........
            }           
            {
              ........
              ........          
            }
          ]
         }    
       ]
      }

You may need to use a multi-dimensional array (array inside array) for this task.

If you're unsure about using the push function with arrays, feel free to ask for guidance. Thanks in advance!

Answer №1

Check out this JavaScript snippet that can help you parse your JSON example file.

function httpGet(url) // Function to fetch JSON file from a Gist
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

var data = JSON.parse(httpGet("https://gist.githubusercontent.com/anonymous/4d342372ed151964bbc03bbad1b4db65/raw/d843d183522f1b16eea1cfc9f3e36c9f22ff5e05/Country.json")); // Store the converted JavaScript object from JSON file (as per your example)

for (var i = 0; i < data.Country.length; i++) // Loop through array of objects in 'data'
{
  console.log(data.Country[i].Country_Name)
  for (var j = 0; j < data.Country[i].Country_Details.length; j++){
    console.log("Country Details - State: "+data.Country[i].Country_Details[j].State_Name)
    console.log("Country Details - Capital: "+data.Country[i].Country_Details[j].Capital)
  }
 
}

Answer №2

If you're looking to efficiently manage file data and convert it to JSON, check out this helpful website: http://jsoneditoronline.org/

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 use CSS in ReactJS to insert an image into a specific area or shape?

Currently, I'm working on developing a team picker tool specifically for Overwatch. The layout consists of cards arranged horizontally on a website, all appearing as blank gray placeholders. These cards are positioned using the JSX code snippet shown ...

Is there a way to automatically hide divs with the style "visibility:hidden" if they are not visible within the viewport?

Currently, I am working on developing a mobile web app. Unfortunately, Safari in iOS 5.1 or earlier has limited memory capabilities. In order to reduce memory usage while using css3 transitions, I have discovered that utilizing the css styles "display:none ...

Switch from using getElementById to useRef in React components

There is a requirement to update a functional component that currently uses getElementById to instead utilize the useRef hook. The original code snippet is as follows: import React, { useState, useEffect, useRef } from 'react'; import { createPo ...

Issue with binding classes dynamically in vue with svg elements

I'm attempting to create a custom typing program for one of my students using SVG to display the words and class binding with Vue.js. The goal is to change the color of the characters when the correct key is pressed by the user. However, I've enc ...

Laravel is unable to interpret formData

I've been on a quest to find answers, but so far I'm coming up empty. I'm trying to send file input to a Laravel controller via Ajax, but it seems like the controller can't read the data at all. Here is my Ajax code: let fd = n ...

Exploring the techniques for displaying and concealing div elements with pure JavaScript

Here's an example of code I wrote to show and hide div elements using pure JavaScript. I noticed that it takes three clicks to initially hide the div elements. After that, it works smoothly. I was attempting to figure out how to display the elements ...

Steps for transforming an array of file names into JSON format and including a specific key

I am in the process of creating a new website that will display all the files contained in a specific folder. However, I am facing an issue with converting an array of document names into JSON format. In order to achieve this, I understand that I need to ...

Unlocking the WiFi Security Key and Accessing Connected Devices with Javascript

When utilizing the command line netsh wlan show interfaces, it displays various information. However, I am specifically interested in extracting the data Profile : 3MobileWiFi-3D71. My goal is to retrieve only the content after the : so that ...

What could be causing the divs to overlap? Without the use of floats or absolute positioning,

When resizing vertically on mobile, my date-time-container is overlapping the upper elements welcome and weather. Despite setting them as block level elements, adding clear: both, and not using absolute positioning or floats, the overlap issue persists. An ...

React - the use of nested objects in combination with useState is causing alterations to the initial

After implementing radio buttons to filter data, I noticed that when filtering nested objects, the originalData is being mutated. Consequently, selecting All again does not revert back to the original data. Can anyone explain why both filteredData and orig ...

Unable to alter the height of the element

I am attempting to resize an element by dragging, similar to this example. I have created a simple directive for this purpose: @Directive({ selector: '[drag-resize]' }) export class DragResizeDirective { private dragging: boolean; const ...

Transform object into JSON format

Is there a way to transform an object into JSON and display it on an HTML page? let userInfo = { firstName: "O", lastName: "K", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b44476b445b05484446">[ema ...

Divs are the preferred placeholders over inputs and textareas

For the past few weeks, I have been trying to tackle a problem with creating placeholders that guide users on where to type. My goal is to make these placeholders disappear when users start typing and reappear if the div is empty again. All my attempts so ...

The jQuery Ajax Error is consistently being triggered

I'm puzzled as to why my custom callback error function keeps getting triggered. When I remove this callback function, the success callback works just fine. Some sources online suggest that it could be an encoding issue, but I don't think that&a ...

Pre-requisites verification in TypeScript

I have a typescript class with various methods for checking variable types. How can I determine which method to use at the beginning of the doProcess() for processing the input? class MyClass { public static arr : any[] = []; // main method public stati ...

What is the best way to transfer variables between two Vue files?

How can I transfer a variable between two Vue files? Hello, in my SendCode.vue file, I have a variable named NewEmail that I would like to use in another file called changePass.vue. Is there any way to do this? Can someone offer assistance? Thank you</p ...

A guide on extracting data from a JSON list of lists in SQL Server

When parsing data from an API in a SQL Server database that is returned in the JSON format provided below, there arises a challenge due to the structure of nested lists within lists: declare @json nvarchar(4000) = N'{ "List":{ " ...

In C++, generate an array containing elements of the div_t structure type

In my current structure, there is a data type named DATE which is of type div_t and contains a year (quot) and a month (mois). typedef div_t DATE; #define ans quot /* (s)(l)div_t : .quot -> .ans... */ #define mois rem /* ... et ...

Page reloads are disabled when Chrome devtools debugger is paused in a React app

Currently, I am in the process of troubleshooting a React application that was created using create-react-app. Whenever I attempt to reload the page while paused on a breakpoint, it results in the page stalling. The screen goes blank and is unresponsive t ...

Merging arrays in PHP

Here is a PHP code snippet that excludes certain Woocommerce categories from Google Merchant Center. How can you condense the use of in_array to shorten the code? // Exclude specific categories from Google Product Feed function exclude_product_from_fee ...