Error message displayed by console when attempting to parse JSON data that is in array

After receiving a simple array as my JSON response:

[35,55]

The Chrome network inspector confirms that it is valid JSON. However, when attempting to parse the xhr.responseText using JSON.parse, I am confronted with the error:

Uncaught SyntaxError: Unexpected token :

I have also experimented with using JSON.stringify and utilizing the array without parsing it in JSON.parse, but unfortunately, JavaScript does not recognize it as an array.

According to JSONLint, the JSON is indeed valid.

At this point, I am unsure of what steps to take next. My goal is to successfully utilize my xhr array as an actual array in JavaScript.

Answer №1

While working with my application, I encountered this error on two separate occasions. My JSON was quite complex compared to yours. Here are the specific scenarios that caused the issue. Make sure that neither of these matches your situation: a. Due to the complexity of my JSON structure, I often missed using commas and sometimes accidentally used curly braces to define an array. b. I needed to align my JavaScript object with a particular class. However, my JSON had two additional values that did not match the class, causing parsing issues. I hope my experience can be beneficial for you!

Answer №2

The problem arose because I mistakenly used JSON.parse again on a variable that had already been parsed using JSON.parse, causing an error.

Let me illustrate my mistake with an example:

var currentJSON = JSON.parse(xhr.responseText);
var oldJSON = [];
if (currentJSON) {
    /* perform operations with currentJSON, such as comparing it with oldJSON */
    oldJSON = JSON.parse(currentJSON); /* <- This is where the mistake occurred */
}

Here is the correct approach:

var currentJSON = JSON.parse(xhr.responseText);
var oldJSON = [];
if (currentJSON) {
    /* perform operations with currentJSON, such as comparing it with oldJSON */
    oldJSON = currentJSON; /* <- Removed unnecessary use of JSON.parse() on currentJSON */
}

Answer №3

It was discovered that the problem stemmed from parsing the JSON data more than once.

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

In Swift 4, decoding may not work correctly when JSON data includes a new line character (" ")

In cases where JSON data in Swift 4 contains a newline ("\n"), decoding may not work properly. If you encounter this issue, there is a workaround you can try. Take a look at the sample code provided below: var userData = """ [ { "userId": 1, "id" ...

The present time lags behind in nodejs by a 6-hour difference

I want to compare the current datetime with the datetime stored in a database column. When I use new Date() on my computer, it gives me datetime as 2023-05-21T04:35:07.903Z, even though my computer time shows 10:35:07. How can I resolve this issue? Please ...

Any suggestions on resolving the message "Unable to locate module './commands/${file}'"?

Can someone assist me in resolving this issue? I am trying to develop a code that includes advanced commands. Here is the code snippet: const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js&apo ...

Encountered difficulty locating the module path 'stream/promises'

When importing the following in a typescript nodejs app import { pipeline } from "stream/promises"; Visual Studio Code (vscode) / eslint is showing an error message Unable to resolve path to module 'stream/promises' This issue appeare ...

I'm encountering a typescript error as I migrate a Paho MQTT function from Angular 1 to Angular 2 - what could be causing this issue?

When connecting to my MQTT broker, I am working on several tasks. In my Ionic 2 and Angular 2 application, I have created an MQTT provider. Here is the provider code: import { Component } from '@angular/core'; import { NavController, ViewControl ...

There seems to be a problem with the sorting functionality on the table in React JS,

My React table is functioning well with all columns except for the country name column. I double-checked the API and everything seems to be in order, but I'm stuck on how to troubleshoot this issue. const Table = () => { const[country, setCount ...

Galaxy S5 browsers experiencing issues with website responsiveness

I've been using jquery to dynamically remove a div in order to change the appearance of my home screen on smaller devices. It's been successful on my Macbook Air and Iphone X, but unfortunately, it doesn't seem to work properly on Android de ...

What could be causing NPM to generate an HTTP Error 400 when trying to publish a package?

My current goal is to release an NPM package named 2680. At the moment, there is no existing package, user, or organization with this specific name. Upon inspection of my package.json, it appears that everything else is in order. Here are all the relevant ...

Complete Form Validation Issue Unresolved by Jquery Validation Plugin

I'm facing an issue with the jQuery validation plugin while attempting to validate a form. Strangely, it only works for one input field. Can anyone suggest a solution? <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.valid ...

Join the nested Observables array

I have an array that holds objects, each containing two properties where one is an observable value. let myArray = [{def: 'name1', value: EventEmitter_}, {def: 'name2', value: EventEmitter_}] My goal is to subscribe to the observables ...

Modify the displayed text according to the content of the input field in HTML

I need to update the value of an <h3> tag based on user input in an input field. Here is my current code snippet: <input id="Medication" name="Medication" size="50" type="text" value=""> <script> $(document).ready(function () { $(&apos ...

For each JSON object, verify whether the value exceeds zero

How can I iterate through each Json result and check if any of the objects (Stage2) have a value greater than 0, then append it to a div? function service(){ var service_id=document.getElementById('down').value; $.ajax({ &a ...

PHP response working inconsistently when called via ajax

My quest involves passing values to a PHP page that should respond with PHP code for loading. However, the issue arises when the returned PHP code only partially functions. AJAX: $.ajax({ type: 'post', url: 'bundles_drop.php', d ...

Utilizing Input Data from One Component in Another - Angular4

As a newcomer to Angular, I'm facing an issue where I need to access a variable from ComponentA in ComponentB. Here's the code snippet that demonstrates what I'm trying to achieve (I want to utilize the "favoriteSeason" input result in the " ...

Decoding JSON using abbreviated keys in C#

I am in the process of transferring a project from Android to Windows Phone 8 and am struggling to find information on how to specify which JSON key corresponds to each object field. In my Android code, I utilized Google GSON and the SerializedName annota ...

I am having trouble generating a pie chart with CodeIgniter

I am struggling to display a pie chart of expenses in percentage with the code provided below. When I run the code, it shows a blank page instead of the desired chart. I would greatly appreciate any help or corrections on the code as I am feeling very conf ...

What is the best way to retrieve data in a controller's method using ajax?

I am attempting to asynchronously send data to a controller's method. Although I thought this would be a simple task, I was unable to find the solution on Stack Overflow. Below is my code: Controller public function actionRaiting(string $idUser, st ...

Utilizing several carets in a single or multiple text areas and input boxes

Just a quick question... Can a textbox have two carets simultaneously, or can we have two separate textboxes both focused at the same time? I am aware of simulating this using keydown listeners but I'm specifically looking for visible carets in both ...

I am not receiving GCM messages on my app, even when the app is not actively running

I am trying to display GCM notifications to users even when my app is closed or cleared from cache memory. Currently, the code I have only works when the app is open but not running in the background: public function send_notification($registatoin_ids, $m ...

Finding MongoDB data using an Express route and displaying it in a Jade template

Is there a way to retrieve data from MongoDB using an express route and display it in a jade template? Below is the code snippet of my express route (express version 2.5.8): app.get('/showData',function(req,res){ db.collection('comme ...