What is the best way to return JSON data as key-value pairs when using the Ajax function $.getJSON()?

Here is the ajax code I'm using to fetch JSON data from a Jobs.json file.

 $(document).ready(function(){
        $('#btn2').click( callJobs );
        });

function callJobs()
{


     alert("getting results...");
    $.getJSON('Jobs.json', function(JSON){
        $('#result').empty();

        $.each(JSON.jobs, function(i, JOB){
            $('#result')
            .append(JOB.Job +'<br />')
            .append(JOB.Priority+'<br />')
            .append(JOB.DueDate+'<br />')
            .append(JOB.Iscompleted+'<hr />');
      });
    });
}

Below is the content of the Jobs.json file:

{
"jobs":[
  {
     "Job":"Job1",
     "Priority":"Low",
     "DueDate":"11.03.2013",
     "Iscompleted":"No"
  },
  {
     "Job":"Job2",
     "Priority":"High",
     "DueDate":"11.03.2013",
     "Iscompleted" : "No"
  },
  {
     "Job":"Job3",
     "Priority":"Medium",
     "DueDate":"11.03.2013",
     "Iscompleted":"No"
  }
  ]
  }

I am looking to improve the dynamic functionality of the $.each() function by making it display the JSON string key and value instead of using .append().

Answer №1

This function will dynamically iterate through the properties of each job:

$.getJSON('Jobs.json', function(JSON){
    var $container = $('#result').empty();

    $.each(JSON.jobs, function(i, JOB) {
        $.each(JOB, function(key, value) {
            $container.append(key + ': ' + value + '<br />');
        });
        $container.append('<hr />');
    }
});

See it in action

Answer №2

Let me break down my approach with some explanatory comments.

$.each(JSON.jobs, function(i, JOB) {
    // Initialize an empty array to store output values
    var values = [];
    // Loop through each property in the current JOB object
    for (var prop in JOB) { 
        // Add each key-value pair to the values array
        values.push(prop + ': ' + JOB[prop]); 
    }
    // Join the array values using '<br />' as a separator; 
    // Append it to #result element and add an '<hr />' afterwards
    $('#result').append(values.join('<br />')).append('<hr />');
});

My main objectives here were to prioritize readability by including an additional array, selecting the #result element only once, and avoiding the need to determine whether to add that last <br /> in each loop iteration. Unlike other solutions, this method does not include an extra <br /> after the final property before the <hr />, which is also consistent with your original solution.

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

How to Query MongoDB and reference an object's properties

I'm trying to execute a script on my MongoDB that will set teacher_ids[] = [document.owner_id]. The field owner_id already exists in all the objects in the collection. Here is my current attempt: db.getCollection('readings').update({ $where ...

What is the reason that dates are not exported correctly in Laravel using jQuery data table when the month is two digits and the file format is EXCEL?

I am trying to export data as an EXCEL file from the view, everything is working fine except for the date format. Here is the code I have tried: $('#get_hourly_report').click(function () { var id = $('#teacher').val(); ...

Performance challenges with an AngularJS application that uses pagination

Resolving Performance Issues in Paginated AngularJS Posts Application I developed a compact application that showcases JSON data as cards using AngularJS and Twitter Bootstrap 4. The app includes pagination with approximately 100 posts per page. var ro ...

AngularJS - Utilizing Angular to work with nested JSON scopes

{ "imports": { "imported": [ { "date": "19/9/2014", "item": [ { "sn": "3366698", "type": "Food", "weight": "10tn." }, { "sn": "3366699", " ...

Error in React countdown functionality

Successfully integrating a vanilla JS countdown into a React component is challenging. Here is how I achieved it: import React, { Component } from 'react'; class CountdownComponent extends Component { constructor(props) { super(prop ...

loading a module's dependencies seamlessly with RequireJS

Currently, I am working with Knockout and Require in my project. I have isolated some Knockout handlers into a separate module that I want to utilize. While there is no specific JavaScript code relying on this module, it is referenced in the data-bind attr ...

The issue with launching a Node.js server in a production environment

I'm currently facing an issue when trying to start my TypeScript app after transpiling it to JavaScript. Here is my tsconfig: { "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "baseUrl": "src", "target": " ...

AngularJS: displaying table columns before data arrival

Is there a way to ensure that AngularJS renders table columns correctly even before receiving the actual content for them? I have been using ng-if to display the content, as I need different elements based on the value returned from an API call. This is w ...

Tips for identifying the cause of a memory leak in browser notifications

I am looking to implement browser notifications in a browser extension. However, I have noticed that the memory usage does not decrease after closing the notification. Can someone explain why this may be happening? Allow StackOverflow show notifications i ...

Unraveling the intricacies of a website template downloaded alongside a webpack ES6 project

My colleague in the office was adamant about purchasing a stunning HTML/CSS/JS external template to serve as a foundational design for our website project. This particular website is a significant endeavor that we are constructing using Laravel, SASS, and ...

Ways to store Token in Browser Cache?

I am currently developing a login system for an application at my school. I have successfully implemented user registration, which is saved to my Azure DocumentDB. However, when trying to log in with the user, the token does not get saved so that I can acc ...

How can I resize and horizontally align an image using html/css?

Is it possible to resize, crop and center an image using only HTML/CSS? (Using the img tag or CSS sprite) For instance, if I have a 500x500 pixel image, I would like to resize it to a 250x250 pixel image To make the actual visible image 100x100 pixe ...

Guide to transmitting and managing a JSON document utilizing JavaScript

When working on the server side, I receive a simple JSON file via REST that contains various IDs. Here is an example: [ { "_id": "5825a49dasdasdasd8417c1b6d5", } "_id": "dfsdfsdf4960932218417c1b6d5", } "_id": "23434344960932218417c1b6d5", },] To handle t ...

Error: Value not defined in the (Node, Express, Pug, JQuery) environment

I'm encountering a common issue as a beginner and could really use some assistance. I have tried multiple solutions but still can't resolve the error "ReferenceError: $ is not defined" when attempting to use jQuery. My project structure looks lik ...

A step-by-step guide on integrating the CSS file of react-datepicker into a Nestjs SSR application with AdminJS

Currently, I am integrating the react-datepicker component into my SSR project built with Nest.js and Admin.js. To ensure that the React components function properly and are styled correctly, I need to include the line 'import 'react-datepicker/d ...

The Gatsby node encounters an error while trying to create a new page

I am currently working on creating sub-pages for a projects category in Gatsby. The parent page for each project is generating correctly, but the sub-pages are not behaving as expected. Each project has the potential to have zero or multiple sub-pages, an ...

associating functions with various events that require arguments

I am working with two event listeners that trigger separate functions, but I believe it might be more efficient to have them trigger the same function instead. These event listeners are monitoring keystrokes and the mouse wheel. $(document).mousewheel(on ...

What is the most effective way to determine if a statement is either false or undefined?

What is the most effective way to determine if a statement is not true or undefined, sometimes without necessarily being a boolean? I am attempting to improve this code. var result = 'sometimes the result is undefined'; if (result === false || ...

What is the process for transmitting information from an express server to a client in Next.js?

I am working on a Next.js web application that uses Express. My goal is to post data to the webpage, fetch it on the server, and then pass it on to my Next.js page. Since I am relatively new to Next.js and Express, I have included my server.js code below: ...

Creating a unique function to map an array in VueJS specifically designed for table manipulation

I am currently working on displaying and sorting data in a bootstrap table within VueJS. My goal is to change the date format within an array retrieved from an API endpoint. The original date format is in "January 21, 2010" and I need it to be in "MM/DD/Y ...