Retrieve the JSON data based on a specific key after a specified period

Hello there, I am encountering an issue with a specific JSON key. Let's say I have an external file containing JSON data structured like this:

{
   "key 1":[
      {
         "linkName":"key name 1.1",
         "linkUrl":"key URL 1.1"
      },
      {
         "linkName":"key name 1.2",
         "linkUrl":"key URL 1.2"
      }
   ],
   "key 2":[
      {
         "linkName":"key name 2.1",
         "linkUrl":"key URL 2.1"
      }
   ],
   "key 3":[
      {
         "linkName":"key name 3.1",
         "linkUrl":"key URL 3.1"
      },
      {
         "linkName":"key name 3.2",
         "linkUrl":"key URL 3.2"
      }
   ]
}

Furthermore, imagine I have implemented a setInterval function to sequentially load data based on the keys. This means that upon page load, key 1 should be displayed first, followed by key 2, and then eventually key 3. I've attempted to achieve this through the following script:

$.getJSON("demo.json",function(data){
   $.each(data,function(key,value){
     if(data.hasOwnProperty(key)){
       var total = new Array();
       for(var i=0; i<2; i++){
       total[i] = key;
       $("#topmost").append('<div>'+total+'</div>');
     }
   }
});
});

The element with ID "topmost" is located within the body/html:

<div id="topmost"></div>

I would appreciate any assistance you can provide regarding this matter.

Answer №1

Hey there, I managed to solve the issue you were facing. Here's a snippet of the code you shared with me:

<script type="text/javascript">
    $(document).ready(function(){       
        $.getJSON("demonew2.json",function(data){
            $.each(data,function(key,value){
                $("#topmost").append('<div>'+key+'</div>');
                if(data.hasOwnProperty(key)){
                    //alert(key);
                    var total = new Array();
                    for(var i=0; i<4; i++){ // Here 4 should be something like counts of the keys, as in this json file it is 4
                        total[i] = key;
                        $("#topmost").append('<div>'+total+'</div>');

                        setInterval (function(){alert(key)},5000);
                        // I NEED THE DATA TO BE LOADED KEY BY KEY, SAY AFTER PAGE LOAD IT WILL DISPLAY THE VALUES OF key_1, THEN AFTER 5 SECONDS<br />
                        // IT SHOULD DISPLAY key_2 VALUES AND SO ON.
                    }
                }
            });
        });
    });
</script>

</head>

<body>

<div style="background:#ccc; border:2px solid #ccc; padding:10px;" id="topmost"></div>

</body>

I identified two main issues in your code:

1) If you want to delay a job, you should use "setTimeout" instead of "setInterval" which repeats the job at a set interval. 2) Using the same delay amount for all jobs will make them execute almost simultaneously, so it's better to increase the delay.

Moreover, directly passing values to setTimeout or setInterval can cause unexpected behaviors due to cross-thread value injections. It's recommended to use a proxy function to avoid direct injection. Here's the updated working code:

    <script type="text/javascript">

        $(document).ready(function () {

            $.getJSON("demonew2.json", function (data) {

                var delay = 0;

                $.each(data, function (key, value) {

                    delay += 5000;

                    showData(key, value, delay);
                });
            });
        });

        function showData(key, value, delay) {

            setTimeout(function () {

                $("#topmost").append('<div>' + key + " = " + JSON.stringify(value) + '</div>');

            }, delay);
        }
    </script>
</head>
<body>
    <div style="background:#ccc; border:2px solid #ccc; padding:10px;" id="topmost"></div>
</body>

Let me know if this resolves your issue. Enjoy! ;)

Update: I've included the full page code for easier usage, and made a slight adjustment to the append section to add a fade effect and make it more interesting:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>


    <script type="text/javascript">

        $(document).ready(function () {

            $.getJSON("demonew2.json", function (data) {

                var delay = 0;

                $.each(data, function (key, value) {

                    delay += 5000;

                    showData(key, value, delay);
                });
            });
        });

        function showData(key, value, delay) {

            setTimeout(function () {

                $("#topmost").fadeOut(function() {
                $("#topmost").append('<div>' + key + " = " + JSON.stringify(value) + '</div>').fadeIn();
            });

            }, delay);
        }
    </script>
</head>
<body>
    <div style="background:#ccc; border:2px solid #ccc; padding:10px;" id="topmost"></div>
</body>
</html>

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

Attempting to coordinate a virtual meeting through the utilization of the Zoom API

I'm currently in the process of developing a website using Node.js, Express.js, and Mongodb. One feature I am working on is the ability for users to schedule Zoom meetings directly within the website. The desired functionality would be for users to sc ...

Encountering a syntax error while trying to parse JSON in a React.js application,

Having trouble fetching data from a JSON file in React.js After checking myJSON on JSLINT and using a Windows system. I'm not attempting to display it yet, just storing it in a variable. However, I keep getting this error : ERROR in ./src/app/docume ...

Focus on a specific data set within a JSON file when working with Backbone.js

Hello! I am new to learning Backbone.js and would love some suggestions from the experts out there. Here is a snippet of my code: app.Collections.UserCollection = Backbone.Collection.extend({ model: app.Models.IdModel, url: "/test/test_data.json" ...

Ways to identify when the socket has been opened by the client?

When utilizing socket.io on the client browser side, is there a way to identify when the socket connection has been successfully opened? I am also interested in monitoring other standard messages such as errors and disconnections. In comparison to the Web ...

Encountering issues with the Sequelize Model.prototype.(customFunction) feature malfunctioning

While attempting to define a customFunction within the Sequelize model, I encountered an error: TypeError: user.getJWT is not a function at User.create.then (/projects/test/a/app/controllers/UserController.js:22:29) Below is the code snippet from ...

Navigating intricate JSON information using AngularJS

I am working on displaying JSON data in an HTML form using ng-repeat. I have managed to retrieve data from some objects, but I am facing challenges due to the nested structure of objects like "Obj => Obj => Obj". In the JSON object provided below, I ...

Is it possible to create a Vue JSX component inside a Single File Component using the <script setup> syntax and then incorporate it into the template of the S

I am impressed by how easily you can create small components within the main component file in React. Is it possible to do something similar with Vue 3 composition API? For example: Component.vue <script setup> const SmallComponent = <div> ...

Is Spring JdbcTemplate capable of cleaning URLs?

During the development of a Spring Boot API, I encountered a small issue that I could use some advice on from someone more experienced with how Spring Boot functions behind the scenes. Within a controller, there is a method marked with @ResponseBody that ...

Why is it that this JavaScript isn't working as intended in the popup form?

</br> s_foot"> * use ajax.jquery as control event. like $("#save").click(function(){.....}); <script type="text/javascript>" var wp; var position; var pid; var product_name; var production_date; In this script, I am attempting to re ...

Submitting a JSON array to an MVC Web API using the POST method

Here is the code snippet I am using: { "myImage": [{ "Image": "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACGUlEQVR4nI2OPWgTcRiHf/9L7isftmkbU/PRYg/LgaI4CBWKCkoCSqVgRTqo6OIgOrgpgojUyUHwA1xEHIUKNggq1ASili6G1sXUVE0ThV4vmNSD3l3u7u/SgGlszG9+nud9gTY2LU ...

Unsure of the response from the $.post request

CHANGE: I keep receiving the object {"readyState":1}. Why is this happening? How can I successfully retrieve the result from the $.post (specifically, the object {"result":"ERROR"})? This pertains to using jEditable. (Please note: This seems more like a ...

jquery token selection dropdown box

I am not encountering any errors with this particular issue, however upon reviewing the plugin it appears that it should only toggle "admin admin" in the dropdown list. I am currently utilizing the most recent version of jquery. Upon further investigation ...

Angular: Unable to retrieve defined data when loading a component

There is a nagging question in my mind that I hesitate to ask because deep down, I know the answer is probably staring me in the face. After struggling with code for two days straight, I am on the brink of pulling my hair out. Although I am relatively new ...

Ways to stop values from being turned into strings in javascript?

let str; let displayedNum; for (let i in imgURLArray){ str = "<li photonum="+i+">" + "<a>"+ (1+i) + "</a>" + "</li>"; $("ul.selection-list").append(str); } While looping through, I encountered an issue wher ...

Display information retrieved from a database in JSON format on the screen using Xcode

class ViewController: UIViewController { @IBOutlet var fname: UILabel! struct Class: Codable { let FName: String let LName: String enum CodingKeys: String, CodingKey { case FName = "first_name" case LName = "last_name" ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

Is it possible to exclude certain static files from being served in express.static?

const express = require('express'); const app = express(); app.use('/app', express.static(path.resolve(__dirname, './app'), { maxage: '600s' })) app.listen(9292, function(err){ if (err) console.log(err); ...

Setting up VideoJS Flash backup

Due to Firefox's restriction on using an .mp4 file in the <video> tag, I am required to utilize the Flash fallback option on my VideoJS player. When it comes to Chrome, Safari, and IE, I can customize my VideoJS player via JavaScript to perform ...

How can I navigate through a webpage using Selenium WebDriver and JavaScript?

Currently, I am utilizing the JavaScript API for selenium-webdriver and my goal is to scroll/move down a page in a gradual manner to facilitate visual inspection. Although I am aware that the code below will direct me immediately to a link at the end of t ...

Is there a safe method to convert an HTML attribute (Javascript Object) into an array using Javascript or JQuery?

I have an HTML element containing a javascript object: <div ui-jq="easyPieChart" ui-options="{ percent: 75, lineWidth: 5, trackColor: '#e8eff0', barColor: ...