Retrieve JSON information from a document through JavaScript

Is it possible to fetch JSON data using JavaScript without relying on jQuery? I am only interested in retrieving data using pure JavaScript.

Here is an example of my JSON file:

{"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_default_view":3,"_deviceID":1,"_deviceName":"MobiTech","_deviceTypeID":1,"_projectID":1,"_roomID":2,"_roomName":"Room2","_room_admin_mail":null}]}

This is what my home.html file looks like:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8>
  <title>JavaScript Get Json</title>

</head>
<body>

<h1>My Home Page</h1>

<div id="results">
    <!-- Display Jason Data -->
</div>

<script>

    var resultDiv = document.getElementById("results");

    var newsURL = "http://localhost:81/testjs/data.json";

    var req;

    if (window.XMLHttpRequest) {
        // code for modern browsers
        req = new XMLHttpRequest();
    } else {
        // code for old IE browsers
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    req.onreadystatechange = function() {

        var html = "";

        if (req.readyState == 4 && req.status == 200) {
            var response = JSON.parse(req.responseText);

            if(typeof(req.responseText)==="string") {
                dataVar = req.responseText;
            } else {
                if (typeof(req.responseXML)==="object") {
                    dataVar = req.responseXML;
                };
            }

            var myData = response['JsonProjectIDResult'];

            //Print results 
            html += myData[0]._capacity+"<br />";
            html += myData[0]._description+"<br />";
            html += myData[0]._dev_default_view+"<br />";
            html += myData[0]._deviceID+"<br />";
            html += myData[0]._deviceName+"<br />";
            html += myData[0]._deviceTypeID+"<br />"; 
            html += myData[0]._projectID+"<br />"; 
            html += myData[0]._roomID+"<br />"; 
            html += myData[0]._roomName+"<br />"; 
            html += myData[0]._room_admin_mail+"<br />";

            resultDiv.innerHTML = html;
        }
    };

    req.open("GET", newsURL, true);
    req.send();

</script>

</body>
</html>

After receiving some helpful advice from friends, I have modified my code accordingly and now it works as expected. Next, I am looking to iterate through the records using a loop. Is it possible to achieve this using JavaScript?

Answer №1

<script>
var resultsContainer = document.getElementById("results");

var dataURL = "http://example.com/data.json";


var xhr;

if (window.XMLHttpRequest) {
    // code for modern browsers
    xhr = new XMLHttpRequest();
} else {
    // code for older versions of IE
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        response = JSON.parse(xhr.responseText);
        
        var jsonData = response['JsonData'];
        
        var htmlContent = '<ul>';
        for(var key in jsonData) {
            if(jsonData.hasOwnProperty(key))
                 htmlContent += '<li>' + key  + ' = ' + jsonData[key] + '</li>';
        }
        htmlContent += '</ul>';
        
        resultsContainer.innerHTML = htmlContent;
    }
}

xhr.open("GET", dataURL, true);
xhr.send();
</script>

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 steps can be taken to ensure that an ObjectID does not transition into a primitive form

Is there a way to avoid an ObjectID from being converted into a primitive data type when transferring in and out of Redis? Would converting it to a JSON string be a possible solution? Thanks! ...

Learn how to implement a captivating animation with JavaScript by utilizing the powerful Raphael Library. Unleash the animation by triggering it with either

My desire is to indicate this movement by triggering a mouse click or drag to the desired location. let myDrawing = Raphael(10,10,400,400); let myCircle = myDrawing.circle(200,200,15); myCircle.attr({fill:'blue', stroke:'red'}); let my ...

Creating Stunning CSS Animations for a Slider Using SVG

Looking for help to create an SVG CSS animation for a slider using a mockup image. The animation will feature a balloon with a number value that zooms in and out from left to right or right to left. Currently stuck at the starting point and unsure how to ...

When trying to access a property in Typescript that may not exist on the object

Imagine having some data in JS like this example const obj = { // 'c' property should never be present a: 1, b: 2, } const keys = ['a', 'b', 'c'] // always contains 'a', 'b', or 'c' ...

React: Updating State with the Spread Operator and Array Method to Add Elements to an Array

Link to my jsfiddle code snippet: https://jsfiddle.net/ilikeflex/r2uws1ez/30/ I've been attempting to update the state in React by accessing the previous state. There are three different cases where I'm trying to achieve this, but I'm havin ...

Is there a way to create a rectangle shape and connect it with data from a Json file on a page

Is it possible to draw rectangles on a page.aspx? For example, by using data from a JSON object like {name:Food;name:Candy;name:Water;name:Meat;......}, where each rectangle corresponds to the count of different data names. If there are 4 names in the data ...

Transforming a JSON data string into a DataTable using Newtonsoft.Json in VB

Here is the string I am working with: [{'Column1': 'c1r1', 'Column2': 'c2r1'},{'Column1': 'c1r2', 'Column2': 'c2r2'}] In Visual Basic, I am trying to convert this string into ...

Reactjs: When components are reused, conflicts may arise in UI changes

I'm currently working on creating a sample chat room application using reactjs and redux for educational purposes. In this scenario, there will be 3 users and the Message_01 component will be reused 3 times. Below is the code snippet: const Main = Re ...

Dynamic loading of JavaScript/HTML content using jQuery Mobile and PhoneGap

I am currently in the process of building a mobile app using Dreamweaver CS6 (with PhoneGap), along with jQuery Mobile and JavaScript. This app aims to gather user-inputted form data, convert it into a JSON object, and send it to a python web service. The ...

Setting a menu item as active in a SvelteKit app: A step-by-step guide

I encountered an issue with the main navigation menu in my sveltekit application. The problem is that when the app is loaded or refreshed, the active menu item corresponding to the current URL is not set. After struggling to find a solution online, I manag ...

Ensuring promise resolutions in a chain using Angular JavaScript before delivering a final result

I have a scenario in Angular where I am using a chain of promises and I want to ensure that a value is returned at the end of the chain: this.calculateeventsattended = function(username) { var Attendees = Parse.Object.extend("Attendees"); var User = ...

Encountering an issue with importing JSON in Python resulting in a BadStatus

Currently, I am attempting to import the Json data that is being generated by an Impinj R420 reader. Here is the code snippet that I have been using: # Importing the necessary libraries import urllib.request from urllib.request import urlopen import json ...

Accessing information stored in an array using JSON

In my PHP script, I am trying to decode a JSON string from a specific URL: $jsonurlpers = "https://api.openarch.nl/1.1/records/show.json?archive=nha&identifier=8554bfba-9fd9-4ca2-876c-feb7da095d6c"; $jsondatapers = file_get_contents($jsonurlpers); Aft ...

Adding properties to a class object in Javascript that are integral to the class

Recently, I've been contemplating the feasibility of achieving a certain task in JavaScript. Given my limited experience in the realm of JavaScript, I appreciate your patience as I navigate through this. To illustrate what I am aiming for, here' ...

Python Selenium- Extract and print text from a dynamic list within a scrolling dropdown element

I am currently working on a project using Selenium and Python to extract a list of company names from a dropdown menu on a javascript-driven webpage. I have successfully managed to reveal the list of company names by clicking the navigation button, and eve ...

Troubleshooting AngularJS: json_encode not producing output under specific circumstances

Currently, I am using $http.get to retrieve data from the server. The controller first calls BackendServices, and within the service, $http.get is invoked: Controller: app.controller('courseController', ['$scope', 'BackendService ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

Analyzing a JSON document and incorporating it into a model

I'm currently working with Django and have written a script. I am attempting to parse a JSON file and integrate it into a model that I created. However, I have encountered a perplexing error that has left me stumped! import os os.environ["DJANGO_SETT ...

Steps to resolve the 'Unknown keyword' issue while packaging a CSS file using webpack

In the process of upgrading dependencies to the latest versions for my Electron app built in Angular, I have encountered some issues. ✅ Electron remains on v19 ✅ Tailwindcss is updated to v3.1.8 ⬆️ Angular is being upgraded from v11 to v14 ⬆️ ...

Using D3 to create SVG elements in Next.js, the mouseenter event only triggers once

I'm currently developing a React Component that utilizes D3, however, I am facing an issue where the SVG circles are only triggered once. import React, { useEffect, useRef, useState } from 'react'; import * as d3 from 'd3'; import ...