There is a JSON issue present, with half of the variables being undefined

Having an issue with my JSON as it throws me an undefined error. What's puzzling is that it recognizes my first variable without any problem.

Below are the codes for better understanding:

JSON

{"Comics":[
{"comic" : 
    {
    "src":"Pictures/Comics/dw.jpg",
    "descr":"Doctor Who has a nice tv show."
    }
},
{"comic" : 
    {
    "src":"Pictures/Comics/spi.jpg",
    "descr":"Spider man is a nice comic \
            The main spider-man comic \
            ended with Peter Parker's \
            death."
    }
},
{"comic" : 
    {
    "src":"Pictures/Comics/gg.jpg",
    "descr":"Power puff girls also has a \
            nice tv show .   \
            You should try watching it."
    }
},
{"comic" : 
    {
"src":"Pictures/Comics/v.jpg",
"descr":"V fo Vendeta is a nice  \
            graphical volume written by\
            Allan Moor who also wrote \
            Watchmen. Those books had a movie."
    }
}


 ]
}

Javascript Code

var arrI = new Array(4);
var arrD = new Array(4);

var x = new XMLHttpRequest;
x.onload = function(){
    if(x.status == 200){
    var txt = JSON.parse(x.responseText);
for(var g = 0; g<txt.Comics.length; g++){
        arrI[g] = txt.Comics[g].comic.src;
        arrD[g] = txt.Comics[g].comic.descr;
        alert(arrD[g]);
    }
    }
}

x.open("GET",'Ajax/ImgCom.json', true);
x.send(null);

The strange part is that the

arrI[g] = txt.Comics[g].comic.src;
is working fine. It alerts the src correctly. However, the issue arises with the desc variable which results in giving me undefined. Even though both have correct paths, I can't understand why this discrepancy exists.

I attempted to rectify using https://jsonlint.com, which showed me the following error:

Error: Parse error on line 5:
....jpg",               "descr": 'Doctor Who has a ni

----------------------^

Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

Desperate for a solution, I even tried changing the " of the desc field to ', but unfortunately, it didn't resolve the problem.

Furthermore, experimenting with the ...=txt.Comics[g].comic[desc] notation also didn't result in getting rid of the undefined value.

I thoroughly reviewed for any typos, but couldn't find any. Perhaps there might be some hidden mistakes causing this issue.

Appreciate your time and assistance in advance.

Answer №1

It's not possible to break up your String values across multiple lines in JSON.

{
"src":"Pictures/Comics/spi.jpg",
"descr":"Spider man is a nice comic \
        The main spider-man comic \
        ended with Peter Parker's \
        death."
}

This should be updated to...

{
"src": "Pictures/Comics/spi.jpg",
"descr": "Spider man is a nice comic The main spider-man comic ended with Peter Parker's death."
}

You may also need to make changes to some of your other entries. For more information, visit Multiline strings in JSON

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 is the best way to calculate the total number of results using ajax?

Encountering an issue with the total count of ajax search results. Getting an error message "Method Illuminate\Database\Eloquent\Collection::total does not exist." when using directives, for example: <div class="searched-item"&g ...

Converting a Kendo dropdownlist to a Kendo multiselect: Step-by-step guide

I am in the process of converting a Kendo dropdownlist into a Kendo multiselect. Role Code: Currently it's a Dropdownlist (in the process of converting to Kendo multiselect). Unfortunately, I'm not achieving the desired output. Here is the cod ...

Modifying pixel colors on a numpy array image through slicing

I previously inquired about changing colors on an image uploaded as a numpy array using opencv (BGR format). The objective was to set any red channel value less than 255 to 255. How to optimize changing the value of a 3d numpy array if it meets a conditio ...

Is it possible to continuously increase the value of a CSS property with each click?

I am trying to implement a feature where the value of an element decreases each time a different element is clicked. Currently, I have the following code: $("#trigger_heritage").click(function () { $(".heritage_content ul").css("margin-left", + -880); ...

Issue with e2e.js file format in Cypress Support

I am trying to save Cypress screenshots into a report using a support file as recommended in the documentation. However, I keep encountering an error: Your supportFile is missing or invalid: support/e2e.js The supportFile must be a .js, .ts, .coffee file ...

How to transfer a parameter in Angular 2

I am currently facing a challenge in passing a value from the HTML file to my component and then incorporating it into my JSON feed URL. While I have successfully transferred the value to the component and displayed it in the HTML file, I am struggling to ...

The Rails application is loading JavaScript three times

I am encountering an issue with my ajax function where it is being triggered multiple times upon click instead of just once. $(document).on('click', '.newGameItem', function() { console.log('start click event'); var a ...

Send the user to a customized dashboard depending on their user role permissions using Vue.js

Currently, I am developing a system that involves handling multiple role-permissions for users. To provide some context, there are 3 distinct users in this scenario: User1 (customer), User2 (employee), and User3 (admin). For each of these user types, I ha ...

Having trouble parsing asynchronous script with cheerio parser

Utilizing cheerio for web crawling poses a challenge when encountering websites with asynchronous scripts. When attempting to extract all the scripts from such websites, they are often missed in the process. Here is an example of the code I am currently us ...

Is it possible to remove the active class when clicking on an active link for a second time

While navigating the web, I stumbled upon a question about adding an active link to the currently clicked menu item. The suggested solution was to implement the following code: $("a").click(function(){ $("a").removeClass("active"); $(this).addCla ...

What is the method for displaying x-axis dates below a highchart?

I'm encountering an issue with Highcharts where dates are not showing under the chart when passing series data as an array of objects. See result image The documentation mentions using an object instead of an array ([1649153340000, 45]docs I need t ...

Why does my ball defy the laws of geometry and refuse to be perfectly round with

I'm attempting to create a simple game in javascript, but I've run into an issue where my circle isn't perfectly round. Despite searching for solutions online for 20 minutes, I haven't been able to resolve the problem. I'm hoping s ...

Is it possible to Use Vuejs 2 to Update MathJax dynamically?

Just figured out how to resolve this issue. Simply bind the data using v-html <div id="app"> <h1 v-html="equation"></h1> <button @click='change'>Change</button> </div> var vm ...

Adding a hyperlink in JSON format

I need help adding a link in JSON format using "a href". Here is the current result I am getting: {"data": [[1,"HPP330","test330 hp","IN","Quiz 1",1,"Edit</a>"]]} However, I would like the result to be in the following format: <code>{"data": ...

Is there a way to display a div element just once in AngularJS?

I only want to print the div once and prevent it from printing again. $scope.printDiv = function(divName) { var printContents = document.getElementById(divName).innerHTML; var popupWin = window.open('', '_blank', 'width=300, ...

Struggling with integrating Appbar and Drawer components in Material UI with ReactJS

I am attempting to create my first app using ReactJS and Material UI, but I am facing some challenges. My main goal is to display a left drawer when the button on the bar is clicked. Here is the code I currently have in my App.jsx file: import React from ...

React Router Redux causing an infinite loop when navigating back

I recently encountered a strange issue with my React + Redux app. I am using React Router in combination with React Router Redux for routing, and I noticed some unexpected behavior. Clicking the back button once takes me from route 0 to -1 successfully. Ho ...

Notification for radio button selected

Looking to trigger an alert message when a radio button is not selected? Check out the code below: <form method=post name="spendform" id="spendform"> <input name="price" type="radio" class="invest-coin-check" id="pricemethod" > <button typ ...

utilizing angularjs and bootstrap to manage multiple button models

Recently delved into learning angularjs and bootstrap. Found a tutorial on creating buttons. <div ng-controller="ButtonsCtrl"> <h4>Checkbox</h4> <pre>{{checkModel}}</pre> <div> <button type="butto ...

Angular directive used to create a nested tree list

Currently struggling with a nested list Directive in Angular. Whenever I attempt to run the code, the browser crashes due to the recursive call of the directive. My goal is to display a new list item if the data's children property contains items. H ...