What is the reason behind receiving the error message "Uncaught SyntaxError: Unexpected token o" while using $.parseJSON() and JSON.parse()

After searching extensively on both SO and Google, I have not been able to find a solution to my issue and I'm feeling stuck. The problem arises when I try to parse an array returned from a PHP page using echo json_encode(). Here is what the array looks like:

[" "," "," "," "," ",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]

Each time I attempt to use JSON.parse(), I encounter the error

Unexpected token o at Object.parse (native)
, and with the jQuery alternative, I receive
Unexpected token o at Function.parse (native)
.

Oddly enough, simply assigning it to the $scope allows me to display it on the page. So, where am I going wrong and how can I rectify this?

Below is a snippet of my controller code:

function myController($scope, memberFactory) {

    response = memberFactory.getMonth("2013-08-01 06:30:00");
    var monthDays = $.parseJSON(response);

    var dates = [];
    for (var i = 0; i < monthDays.length; i++) {
        if (i % 7 == 0) dates.push([]);
        dates[dates.length - 1].push(monthDays[i]);
    }
    $scope.dates = dates;
}

This is the relevant service method implementation:

obj.getMonth = function (date) {
    var month = $q.defer();
    $http.get('getMonth.php?date=' + date)
        .success(function (data, status, headers, config) {
        month.resolve(data);
    });

    return month.promise;
}

And here's the corresponding PHP code:

<?php 
$daysOfMonth=[ " ", " ", " ", " ", " ",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31];
echo json_encode($daysOfMonth); 
?>

Attempted Solutions

Upon checking the typeof of the response which reveals it as an Object, I tried various solutions mentioned in answers such as

var monthDays  = Array.prototype.slice.call(response)
and
var monthDays  = $.map(response, function (value, key) { return value; });
. Additionally, I experimented with JSON.stringify() but only ended up with {} as the output.

This issue has become quite frustrating, and I truly need some guidance in the right direction.

Update

I suspect that the problem lies within my usage of $q.defer(). As a result, I made adjustments to the getMonth method:

obj.getMonth = function (date) {
    var month = $q.defer();
    $http.get('getMonth.php?date=' + date)
        .success(function (data, status, headers, config) {
        month.resolve(data);
        console.log("data " + data[0]);
        console.log("resolved " + month.promise[0]);

    });

    return month.promise;
}   

Now, upon logging console.log("data " + data[0]);, I correctly see '1' displayed. However, when I log console.log(month), I receive '[object Object]', and for console.log(month.promise) as well as console.log(month.promise[0]), I get 'undefined'.

Answer №1

response has already been parsed, no need to re-parse it.

If you attempt to parse it again, it will undergo a toString-cast first resulting in parsing

"[object Object]"

hence the occurrence of unexpected token o.

Answer №2

Kindly refer to the section Converting Requests and Answers in the $http module.

If a JSON response is identified, convert it with a JSON parser.

As the data is already formatted as a JSON object, attempting to parse it again will result in an error.

Here's a straightforward demonstration:

response = '{"x": "x","y": "y"}';
var newObj = $.parseJSON(response);
console.log(newObj); //Object {x: "x", y: "y"} 
$.parseJSON(newObj)  //Uncaught SyntaxError: Unexpected token o 

Answer №3

Special thanks to @CuongLe for guiding me through the solution which can be found here. The issue was resolved by making a modification in the code:

response = memberFactory.getMonth("2013-08-01 06:30:00");
 var monthDays = $.parseJSON(response);

Replaced by:

response = memberFactory.getMonth("2013-08-01 06:30:00");
response.then(

function (monthDays) {
    console.log("monthDays : " + monthDays + " !!!");

    var dates = [];
    for (var i = 0; i < monthDays.length; i++) {
        if (i % 7 == 0) dates.push([]);
        dates[dates.length - 1].push(monthDays[i]);
    }

    $scope.dates = dates;
});

Answer №4

If you include the following header:

Content-Type: text/json

Then there is no need to invoke parseJSON(). For instance:

In PHP, I would establish the header in this manner:

<?php
header("Content-Type: text/json");
echo json_encode(array("someKey" => "someValue"));

And in JavaScript, the success function may look like this:

success: function(response) {
// The value of "someValue" will be displayed in the console.
// Since the header was sent as text/json, we do not have to use parseJSON()
console.log(response.someKey);
}

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

Changing the size of various types of images

Is there a way in JavaScript to automatically resize and fill in a block with fixed width using different images with various dimensions? I came across something similar, but it was in AS2. I'm unsure if it can be translated to JavaScript. var _loc3 ...

Executing a keystroke in Selenium Webdriver using JavaScript

I've been writing a test using Selenium WebDriverJS, and now I need to simulate pressing a key on the keyboard. Is it possible to do this with Selenium WebDriverJS? If so, how can it be done? In Java, we achieve this as follows: driver.findElement(Lo ...

Is it possible to retrieve a physical address using PHP or Javascript?

Is it possible to retrieve the physical address (Mac Address) using php or javascript? I need to be able to distinguish each system on my website as either being on the same network or different. Thank you ...

A guide on incorporating and utilizing third-party Cordova plugins in Ionic 5

Attempting to implement this plugin in my Ionic 5 application: https://www.npmjs.com/package/cordova-plugin-k-nfc-acr122u I have added the plugin using cordova plugin add cordova-plugin-k-nfc-acr122u but I am unsure of how to use it. The plugin declares: ...

Angular directive: Exploring the disparities between controller scope and link function scope

As I delve into the world of Angular directives, the concept of scope is proving to be quite challenging for me. Let's consider a custom directive named parentDirective, which has both a controller property and a link property: angular.module("app"). ...

Whenever a click event is triggered, the Vue method is executed twice

Why is the set method being executed twice? Check the console when you click the star. Removing @click="set(rating)" results in no action, indicating it is not called elsewhere. http://jsfiddle.net/q22tqoLu/ HTML <div id="star-app" v-cloak> ...

Ensuring payload integrity using microrouter: A step-by-step guide

I have utilized this code to develop a microservice const { json, send } = require('micro') const { router, post } = require('microrouter') const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY) console.log(process.e ...

Adding extra text dynamically with jquery or javascript

Is it feasible to add extra text to HTML elements using jquery or javascript? If the paragraph element already contains the word "Down", I would like to add the word "full" following it, resulting in "Down full". Is this achievable? If so, which approach ...

Remove any actions that a view has linked to the app.vent

By invoking view.unbindAll(), will the events that I registered on the global event bus be removed? ...

Converting SWIG JSON objects into JSON objects on the client side

Currently, I am implementing Angularjs, although it seems like basic JavaScript can also do the trick. A summary of what has been achieved so far: console.log(JSON.parse({{{JSON.stringify(items)}}})); The variable items contains a JSON object. However, ...

Transform Django Model Instance from Serialized Back to Object using Ajax

Currently, I'm utilizing Ajax to search for a model instance. Once found, I return that instance and pass it as a variable to a template tag within my template. To achieve this, in my view, I serialize the object before sending it to the Ajax success ...

Working with Angular's forEach method and handling null values

I'm encountering an issue where the array of selected devices is not getting the values when attempting to add multiple devices to a group. Can someone identify the problem or suggest an alternative method? I referred to http://www.dotnetawesome.com/2 ...

Video streaming platform without the need for javascript and plugins

Is it feasible to watch Youtube videos without relying on javascript and plugins, exclusively using HTML5 or a similar alternative? ...

What is the best way to create a button with this functionality?

In the form that I have created, it is opened in a bootstrap modal style. This form contains a button that, when clicked, triggers an alert box to appear. The code snippet used for this functionality is as follows: echo "<script>"; echo "alert(&apos ...

Creating a link with a POST method and without using a new line

I am attempting to generate a square matrix and send data using the post method. I have discovered a solution involving JavaScript and form submission, but each time a new form is created, it results in a new line being added. Alternatively, if I move th ...

Trouble Arising from Making a POST Request to Spotify's API

I am currently developing a web application that allows users to search the Spotify Library, add songs to playlists, and then save those playlists to their Spotify Accounts. Almost everything is functioning correctly except for the saving of playlists thro ...

What techniques can I use to adjust the size of an image through zooming in and out?

In my custom gallery component, the crucial code section looks like this: <Gallery> <Header> <img src={galleryIcon} alt='Galley icon' /> <h1>My Gallery</h1> </Header> ...

The essence of the argument becomes muddled when implementing bind apply with arrays as arguments

I referenced this particular solution to create a new instance of a class by passing array arguments using the code snippet below: new ( Cls.bind.apply( Cls, arguments ) )(); However, I encountered an issue where one of my arguments is an array and the v ...

What are the appropriate situations for utilizing getStaticPaths()?

Right now, an API call is being made in a main component and the fetched data is saved in a Singleton. This singleton data needs to be accessed by the getStaticPaths() function. However, due to the fact that getStaticPaths() pre-renders it, the singleton ...

Failed Socket.IO Cross-Origin Resource Sharing request

In the client-side code of my Angular module, I have the following setup for a socket client: angular.module('App') .factory('socketClient', function(socketFactory, Auth) { // Auto-configuring socket.io connection with authentic ...