What could be causing this JSON file to be displaying in an unusual manner?

I am currently working with a JSON document that has been validated using JSlint.

The JSON data is structured like this:

[{
    "date": "2017-02-10",
    " action": "Do a thing",
    "state": "closed",
    "url": "https:someurl.com"
}, 
....

Additionally, I have some HTML code here which is designed to read and display the JSON content.

This is what the HTML code looks like:

<html>

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

<body>
    <script>
        deadlines = []
        start();

        function start() {
            var req = new XMLHttpRequest();
            req.open("GET", "http://joereddington.com/deadlines.json");
            req.overrideMimeType("application/json");
            req.send(null);
            req.onreadystatechange = function() {
                if (req.readyState == 4 && req.status == 200) {
                    var obj = JSON.parse(req.responseText);
                    deadlines = obj
                    for (deadline in deadlines) {
                        var output = '';
                        for (var property in deadline) {
                            console.log(property)
                            output += property + ': ' + deadline[property] + '; ';
                        }
                        console.log(output);
                        console.log(deadline.date)
                        console.log(deadline.action)
                    }
                }
            };
        }
    </script>

</body>

However, I am encountering an issue where listing the properties of each object yields unexpected results:

https://i.sstatic.net/pCmst.png

This outcome is not what I expected. Can someone help me identify the mistake in my implementation?

Answer №1

$.each(JSON.parse(deadlines), function (index, deadline) {
    var result = '';
    for (var prop in deadline) {
        console.log(prop)
        result += prop + ': ' + deadline[prop] + '; ';
    }
    console.log(result);
    console.log(deadline.date);
    console.log(deadline.action);
});

Your JSON object has unnecessary spaces. Make sure it is "action" and not " action".

Answer №2

for...in iterates over the keys (since it's an array: "0", "1" ...). Consider using for...of or forEach or a simple for loop.

I suggest using forEach in this way:

deadlines.forEach(function(deadline) {
    // ...   
});

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

Tips for modifying the response of an ExpressJS server following a timeout on a POST request

Currently, I'm in the process of creating a server using Node.js and ExpressJS. The issue arises when the client sends a POST request instructing the server to control an external device's movement either up or down. My goal is for the server t ...

Create a basic search functionality in an Express Node.js application

Recently, I decided to work on a project to enhance my coding skills. I wanted to create a simple search functionality where the URL would be "/search/(parameter here)" and display products whose names match the parameter. After writing a middleware for t ...

Using the JavaScript validator library for data validation

Looking to utilize the validator in my express project. Is there a way to import only specific packages directly? For example: import {isEmail, isEmpty} from 'validator'; Alternatively, importing each on a separate line. Curious if there is a ...

Utilizing URLs as video sources in the @google/generative AI framework within a Next.js environment

Currently, I am facing an issue while trying to upload videos from a URL using @google/generative-ai in Next.js. While I have successfully learned how to work with videos stored on my local machine, I am struggling to do the same with videos from external ...

Transferring data seamlessly between AJAX and PHP

<?php //Establishing site root variable; ?> <?php require_once("../includes/site_init.php"); ?> <!DOCTYPE HTML> <html lang = "en"> <head> <meta charset = "UTF-8"> <meta name = "viewport" content = "width ...

Error in Django & Angular 2: {_dataService is not defined}

I recently tried incorporating Angular 2 into my Django application as a frontend. However, I encountered an issue while attempting to create a GET request. Angular 2 kept throwing me an error that I couldn't paste here due to formatting constraints. ...

Displaying a message text upon successful AJAX request

I have a web page with an AJAX request that updates data in the database. After the update, I want to display a message to the user on the webpage confirming that the data has been successfully updated. However, currently, no message is being displayed and ...

AngularJS Get request unable to fetch image URL due to receiving a "302 found" error

Trying to enhance my AngularJS app by incorporating an image from a random cat image site, using the URL received. Below is the snippet from my controller.js: 'use strict'; /* Controllers */ var catPath = "http://thecatapi.com/api/images/get? ...

Identify the element in the array that corresponds to the current route

Within an array, I have various routes such as: /app/manual/:id /app/manuals/:id /app/feedback ... In my react.js application, I am looking to compare the location.pathname with the paths in my array and retrieve the title associated with the matching pa ...

Executing JavaScript code from an external HTML file

My goal is to create and utilize native web components by defining them as HTML files containing markup, CSS, and Javascript all bundled together in one file, similar to how Vue handles .vue files. These components would be fetched from an external compone ...

What is the solution to fixing the JSON parsing error that says 'JSON.parse: bad control character in string literal'?

When sending data from NodeJS Backend to the client, I utilize the following code: res.end(filex.replace("<userdata>", JSON.stringify({name:user.name, uid:user._id, profile:user.profile}) )) //No errors occur here and the object is successfully stri ...

Extension for capturing videos on Chrome or Firefox

I am interested in developing a Chrome or Firefox extension that can capture video from a window or tab. My goal is to record full screen videos, such as those on YouTube, for offline viewing similar to a DVR for online content. Creating an extension see ...

How can I send styles to a child component and utilize them as scoped styles within Vue?

One of my components is a parent: <template> <ChildComponent :styles="styles" /> </template> <script> export default { data: () => ({ styles: ` p { color: red } ` ...

The Nivo Slider experiences compatibility issues with webkit browsers when used in conjunction with Really Simple History (RSH) technology

I'm in the process of developing a website with AJAX capabilities, utilizing the Really Simple History (RSH) framework to manage back and forward requests. One challenge I've encountered is that when using Nivo Slider for a slideshow feature, it ...

React Express Error: Unable to access property 'then' of undefined

I'm facing an issue while trying to server-side render my react app for users who have disabled JavaScript and also for better search engine optimization. However, I am encountering the following error: TypeError: Cannot read property 'then' ...

Determine the distance needed to cover the full field of view (

Currently, I am attempting to determine the maximum distance that the camera can zoom in on a sphere while still keeping the entire sphere visible on the screen. var dist = diameter / (2 * Math.tan( camera.fov * (Math.PI/180) / 2 )); The issue is that z ...

"Want to learn how to dynamically disable an input field in AngularJS when another field is selected? Find out how to achieve this using the

Hey there, I'm dealing with two input fields. Input field A is a drop-down menu and input field B. They both have the same value (same ng-model). My goal is to clear the second input field whenever the user selects an option from the dropdown. Can any ...

Ways to display URL parameters on an HTML page without using PHP

I'm currently working on a website using HTML (without PHP) and I'm facing an issue with displaying URL parameters on an appointment confirmation page. The appointment details are being successfully passed through the URL parameters, but I'm ...

Tips for guaranteeing synchronous loading in your angularjs app.js

Here's the code I'm working with: getTens.getToken($rootScope.webUserInfo[0].username).then(function(resulttoken) { $rootScope.userInfo = resulttoken; $sessionStorage.token = resulttoken[0].token; $sessionStorage.user ...

Handling onclick events in Scrapy Splash: A comprehensive guide

I am attempting to extract data from the following website I have managed to receive a response, but I am unsure how to access the inner data of the items below for scraping: It seems that accessing the items requires handling JavaScript and pagination. ...