Tips for formatting JSON using jQuery

Imagine my JSON data with 3 different sets of information:

[  
   {  
      "Pair":"",
      "Id":"8ca2df56-2523-4bc3-a648-61ec4debcaaf",
      "PubDate":"/Date(1463775846000)/",
      "Provider":null,
      "Market":""
   },
   {  
      "Pair":"",
      "Id":"74b2d7c7-bc2c-40ee-8245-7c698befa54d",
      "PubDate":"/Date(1463775247000)/",
      "Provider":null,
      "Market":""
   },
   {  
      "Pair":"",
      "Id":"0ee3cd96-1df8-49ba-b175-7a75d0840973",
      "PubDate":"/Date(1463773687000)/",
      "Provider":null,
      "Market":""
   }
]

Here is what I have already tried:

JQUERY

$.ajax({ 
            type: 'GET', 
            url: 'news.json', 
            data: { get_param: 'value' }, 
            dataType: 'json',
            success: function (data) { 
                console.log(data);
                $.each(data, function(index, element) {
                   $( ".content-news h3" ).append(  data[0].Title  );
                   /** Stuck Here and it only call 1 data but i already use each function **/
                });
            }
        });

HTML

    <div class="news">

                        <div class="ano">
                            <div class="content-news">
                                <h3 id="jtitle"> **/** I Want to Show Id Here **/** </h3>
                                <h4 id="jprovider" class="author">**/** I Want To Show  PubDate **/**</h4>
                                <p id="jsummary">
**/** I Want to Show Provider Here **/**
                                </p>
                                <div class="img-head" id="img-container">
    <!--                            <img src="" alt="img" class="img-responsive">-->
                                </div>
                            </div>
                            <div class="social-control">
                                <div class="head-control">
                                    <p id="jdate" class="inline gray"></p>
                                    <a href="#"><p class="pull-right">show more</p></a>
                                </div>
                                <div class="clear"></div>
                                <div class="footer-control">
                                    <p><a href="#"><i class="ion-ios-heart ion-spacing"></i>20</a></p>
                                    <p><a href="#" data-toggle="modal" data-target="#myModal"><i class="ion-chatbox ion-spacing"></i>2 comments</a></p>
                                    <p><a href="#"><i class="ion-android-share-alt ion-spacing"></i>share</a></p> 
                                </div>
                            </div>
                        </div>





                    </div>

JSFiddle

I am currently only able to display one result. Can anyone provide hints or tips on how to properly template jQuery using JSON? I appreciate any guidance. Thank you.

At the moment, I am only getting results for one set of data displayed: https://i.sstatic.net/ZIXtQ.png

Answer №1

To access the properties through the index in the data property, follow this method:

$.ajax({
    type: 'GET',
    url: 'news.json',
    data: {
        get_param: 'value'
    },
    dataType: 'json',
    success: function(data) {
        //console.log(data);
        $.each(data, function(index, element) {
            console.log(
                data[index].Id,
                data[index].Pair,
                data[index].PubDate,
                data[index].Provider,
                data[index].Market
            );
        });
    }
});

This will output:

8ca2df56-2523-4bc3-a648-61ec4debcaaf  /Date(1463775846000)/ null 
74b2d7c7-bc2c-40ee-8245-7c698befa54d  /Date(1463775247000)/ null 
0ee3cd96-1df8-49ba-b175-7a75d0840973  /Date(1463773687000)/ null 

To handle the templating, you can define a function that generates the markup for each item:

function template(title, provider, summary) {
    var $temp = $('<div/>');
    $temp.append($('<h3/>', {
        text: title
    }));
    $temp.append($('<h4/>', {
        text: provider,
        class: 'author'
    }));
    $temp.append($('<p/>', {
        text: summary
    }));
    console.log($temp);
    return $temp;
}

$.ajax({
    type: 'GET',
    url: 'https://cdn.rawgit.com/enki-code/4ec2b6efa84dfed8922b390d2a1a4c5a/raw/dc94405f12d1d5105e54584a6c53ca30d1863b4a/so.json',
    data: {
        get_param: 'value'
    },
    dataType: 'json',
    success: function(data) {
        //console.log(data);
        $.each(data, function(index, element) {
            $('.content-news').append(template(data[index].Id, data[index].PubDate, data[index].Provider));
            console.log(
                data[index].Id,
                data[index].Pair,
                data[index].PubDate,
                data[index].Provider,
                data[index].Market
            );
        });
    }
});

An updated version of the fiddle provides an example.

You may need to tweak the CSS and other elements for custom styling.

Answer №2

To successfully parse the JSON file containing an array of objects, it is important to iterate through each object individually.

When working with serialized arrays, avoid using each as it consumes more time. Instead, opt for a standard for loop.

You can view the solution on JSFiddle: jsfiddle.net/robert11094/65zjvy5k/3

Alternatively, you can use the provided HTML page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>

<script>
    $(document).ready(function () {
        $.ajax({
            type: 'GET',
            url: 'http://subscriptions.fxstreet.com/json/news.aspx?c=A0DC975D13C44CE697EC&i=englishnewscharts',
            data: { get_param: 'value' },
            dataType: 'json',
            success: function (data) {
                console.log(data);
                for (var i = 0; i < data.length; i++) {
                    var html =
                        '<div class="ano">' +
                        '    <div class="content-news">' +
                        '        <h3 id="jtitle"> ' + data[i].Id + ' </h3>' +
                        '        <h4 id="jprovider" class="author">' + data[i].PubDate + '</h4>' +
                        '        <p id="jsummary">' +
                        data[i].Provider +
                        '        </p>' +
                        '        <div class="img-head" id="img-container">' +
                        '            <!-- <img src="" alt="img" class="img-responsive">-->' +
                        '        </div>' +
                        '    </div>' +
                        '    <div class="social-control">' +
                        '        <div class="head-control">' +
                        '        <p id="jdate" class="inline gray"></p>' +
                        '        <a href="#"><p class="pull-right">show more</p></a>' +
                        '    </div>' +
                        '    <div class="clear"></div>' +
                        '        <div class="footer-control">' +
                        '            <p><a href="#"><i class="ion-ios-heart ion-spacing"></i>20</a></p>' +
                        '            <p><a href="#" data-toggle="modal" data-target="#myModal"><i class="ion-chatbox ion-spacing"></i>2 comments</a></p>' +
                        '            <p><a href="#"><i class="ion-android-share-alt ion-spacing"></i>share</a></p>' +
                        '        </div>' +
                        '    </div>' +
                        '</div>';
                    $('.news').append(html);
                }
            }
        });
    });
</script>
<div class="news">
    <div class="ano">
        <div class="content-news">
            <h3 id="jtitle">Hello World</h3>
            <h4 id="jprovider" class="author">David</h4>
            <p id="jsummary">
                This is content
            </p>
            <div class="img-head" id="img-container">
                <!--                            <img src="" alt="img" class="img-responsive">-->
            </div>
        </div>
        <div class="social-control">
            <div class="head-control">
                <p id="jdate" class="inline gray"></p>
                <a href="#"><p class="pull-right">show more</p></a>
            </div>
            <div class="clear"></div>
            <div class="footer-control">
                <p><a href="#"><i class="ion-ios-heart ion-spacing"></i>20</a></p>
                <p><a href="#" data-toggle="modal" data-target="#myModal"><i class="ion-chatbox ion-spacing"></i>2 comments</a></p>
                <p><a href="#"><i class="ion-android-share-alt ion-spacing"></i>share</a></p>
            </div>
        </div>
    </div>
</div>

Answer №3

Consider utilizing either $.parseJSON or $.getJSON for a smoother problem-solving process.
Source: jQuery Documentation

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

Having difficulty altering the font in the WordPress tinymce editor

I've been attempting to update the font in the WordPress tinymce editor, but I'm running into issues. First, I created a tinymce-custom-editor.css file with the following code: @import url(https://fonts.googleapis.com/css?family=Open+Sans:400,7 ...

Positioning the div to align perfectly alongside the list items

My current objective involves dynamically creating div elements and populating them with items. A working demo of my progress can be found by following this link. The issue at hand is that the newly created div does not appear in the desired location, but ...

Choosing and transferring the table data to be shown in the pop-up box

Having encountered an issue with a popup trigger placed inside a td element, I am seeking advice on how to pass table data into the popup window. Unfortunately, the main popup window was positioned outside the while loop, resulting in multiple instances of ...

Utilizing BootStrap 4 to ensure uniform image sizes within a row of columns

I'm facing a challenge in creating a row of 4 images that are responsive and uniform in size, despite being different dimensions (640x799, 640x479, ...). I've attempted to use columns and img-fluid to achieve this, but the shorter images do not f ...

Troubleshooting height adjustment for header and footer in CSS with dynamic content not functioning properly on Safari for macOS and Safari for iOS (jsBin)

I recently came across a solution by @RokoC.Buljan, which works perfectly on Chrome and Firefox. However, I encountered an issue with Safari where the content section does not scroll properly and the footer sticks to the bottom of the content, making it di ...

Having trouble with the pagination feature while filtering the list on the vue-paginate node

In my current project, I have integrated pagination using the vue-paginate node. Additionally, I have also implemented filtering functionality using vue-pagination, which is working seamlessly. Everything works as expected when I enter a search term that d ...

"Create a set of arrays within an object that are duplicates four times, and then dynamically manipulate the first item within each array

Here is the layout of my array object: const foo = {"data":[ [1,'asdf'], [2,'lorem'], [3,'impsum'], [4,'test'], [5,'omg'], ]} I am looking to replicate each array four times and increment the first item ...

Email - symbols appearing in received message

Today, I am testing out sending an email to myself with values inserted into a form. However, when I receive the email, the formatting appears strange and the characters "\r\n" are visible. I attempted using "%0D%0A," " ", and "PHP_EOL," but the ...

How to eliminate an item from an array using index in JavaScript with jQuery

In order to remove a specific array added in an object by index, I would like the functionality where when a user clicks on a button, it removes the corresponding array. Here's what I have in mind: HTML: <button>1</button> <button>2 ...

How can I remove all rows from a table in MySQL?

I am currently in the process of developing a basic chat application that allows users to post messages and includes an option for resetting the chat by deleting all messages from the database. However, I have encountered an issue where the reset button on ...

What is the significance of using the "why" in the href property within the

I need help understanding why the plus "+" is used before and after myUrl in the function .not. Even though it works fine with or without the +, I am curious about why it was included in the code snippet. <script type="text/javascript"> $(documen ...

Tips for accessing a DOM element's ::before content using JavaScript

Is there a way to retrieve the content of a DOM element's ::before pseudo-element that was applied using CSS3? I've attempted several methods without success, and I'm feeling very confused! // https://rollbar.com/docs/ const links = docum ...

Load a fresh page automatically upon reaching the bottom of the current page

Is it possible to automatically load a new page when a user reaches the bottom of a webpage? For example, imagine a user is viewing page A. As they scroll down to the bottom of page A, page B would automatically load without the need to refresh the page ( ...

Arrange flex list items in vertical rows on smaller screens for a more organized layout

Struggling to have CSS flex list stagger text on two lines for smaller screens, but so far, my attempts have failed. I've tried using spans and br at various media queries, but nothing seems to work. Any assistance would be greatly appreciated. This ...

Is there a way to avoid overlapping in CSS3 transforms?

Check out my jsfiddle demo: http://jsfiddle.net/WLJUC/ I have noticed that when you click to rotate the larger container, it overlaps the smaller one. This poses a problem as I am attempting to create a picture gallery where users can rotate and enlarge ...

Node and Socket.IO - Personalized messaging (one-on-one)

I'm in the process of developing a one-on-one chat feature using Socket.IO and Express to enable private messaging between users. The main issue at hand is: I am looking for a way to send a private message to a specific socket.id while ensuring that ...

Why is my backend sending two Objects in the http response instead of just one?

When I receive data from my Django backend, sometimes instead of one object I get two objects within the HTTP response. This inconsistency is puzzling because it occurs intermittently - at times there's only one object, while other times there are two ...

Populate an HTML table with the days of the month and corresponding dates retrieved from a PostgreSQL database using JavaScript

I'm struggling to figure out how to use generate_series to populate an HTML table where the 'key' of <tr> corresponds to the days of the selected month and year using an <input type='month'>. So far, with the help I re ...

sole active component present

In my redux store, I have an array called rooms that is fetched from the server. In my component, I fetch this array from the store, map it, and display elements with the value of room['foo']. However, I am facing a problem where when a user clic ...

Is utilizing React's useEffect hook along with creating your own asynchronous function to fetch data the best approach

After attempting to craft a function for retrieving data from the server, I successfully made it work. However, I am uncertain if this is the correct approach. I utilized a function component to fetch data, incorporating useState, useEffect, and Async/Awa ...