The unexpected token in the data encoding for JSON.parse() was not anticipated

While working on pulling data from my server, manipulating it, and attempting to load the string into an object using JSON.parse(), I encountered an issue with an 'Unexpected Token' error. It was strange because usually Chrome would specify the unexpected token (typically 'o' or similar), but this time it was just a space. This led me to suspect some sort of ASCII encoding problem. Interestingly, if I printed the JSON string to the console using console.log() and directly pasted it into the code, it parsed without any issues.

 var testString = '[ { "pk": 1663, "state": "IO", "group": "ALO", "species": "", "application_link": "" } ]';
var testObject = JSON.parse(testString);
alert(testObject);

The above snippet works as expected, while the following does not:

function hex2ascii(hexx) {
    var hex = hexx.toString();
    var str = '';
    for (var i = 0; i < hex.length; i += 2)
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    return str;
}

function decodeData(encoded){
    var original_string = '';
    for (var i = 0; i < encoded.length; i+=2) {
        var index = i/2;
        var hex_value = encoded[i]+encoded[i+1];
        var ochar = hex2ascii(hex_value);
        original_string += ochar;
    }
    return original_string;
}
$.get(url, function(data) {
     var testString = decodeData(data);
    var testObject = JSON.parse(testString);
    alert(testObject);
});

I'm looking for suggestions on how best to troubleshoot this situation.

Edit: Upon further inspection, I noticed several null characters in my string. When converting the JSON string back to hex, I received:

hex_string = ''
for(var i = 0; i < decoded_data.length; i++){
    if (i < 10){ 
        alert(decoded_data[i]);
    }
    hex_string += ascii2hex(decoded_data[i])+' ';
}
console.log(hex_string);

>>>0 0 5b 0 0 7b 0 0 22 0 0 70 0 0 6b 0 0 22 0 0 3a 0 0 20 0 0 31 0 0 36 0 0 36 0 0

Edit again:

After some investigation, I found that the issue stemmed from the concatenation method within the decodeData function. When concatenating using

original_string += ochar;

It was adding numerous null characters. Is there an alternative way to concatenate the string?

Edit answer:

Following further exploration, I discovered that the problem originated from the hex2ascii function, which introduced unnecessary null characters. Since I had borrowed the code from Stack Overflow, it wasn't functioning as expected. By making modifications, I managed to resolve the issue:

function hex2ascii(hexx) {
   var hex = hexx.toString();
   return String.fromCharCode(parseInt(hex, 16));
}

Answer №1

It is not possible to simply enter a line break in a JavaScript string, as it will render the string invalid.

Invalid

var exampleString = '[ {
        "id": 123,
        "category": "AB",
        "type": "CD",
        "name": ""
]}';

Valid

var exampleString = '[ {"id": 123,"category": "AB","type": "CD","name": ""]}';

Answer №2

It appears that the Unexpected Token error is being triggered by an additional closing parenthesis on the following line:

$.get(url, function(data)) {

Make sure to add a missing parenthesis at the end of the line.

Answer №3

Aha! I finally discovered where the issue was coming from - the hex2ascii function was causing havoc by including a multitude of null characters. Initially sourced from Stack Overflow, the code didn't quite meet my expectations. After making some modifications, it now works flawlessly.

function hexToAscii(hexCode) {
   var hex = hexCode.toString();
   return String.fromCharCode(parseInt(hex, 16));
}

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

Guide to using AES-256-CBC encryption in Node.js and decrypting with OpenSSL on a Linux system

Question: Hello there, I am currently facing an issue with decrypting my encoded base64 using a specific command. Here is the command that I am trying to use: echo "base64key" | (openssl enc -AES-256-cbc -d -a -pass "pass:test" -pbkdf2 ...

How about making an Ajax request for each item in the array?

I have a task to perform Ajax calls for each item in an array and then trigger another function once all the calls are completed. Adding complexity, I am incorporating Papa Parse into making the Ajax call. This is the code snippet: getCsvData: function( ...

Steps to invoking an asynchronous function within another async function

Is there a way for me to transform the following function into an Async function? I need to invoke several methods based on the result of the function call when isMaxAttemptExceeded has been fully executed. let isMaxAttemptExceeded = async () =&g ...

The presence of an unauthorized token within the meteor/node module has been detected, specifically related

While following g00glen00b's tutorial on meteor/twitter integration (), I encountered a persistent error. Any assistance or clues would be greatly appreciated. Steps I've Taken Uninstall/reinstall npm Uninstall/reinstall twitter package Uninst ...

Slice the edges of the depth on a shape created with ThreeJS ExtrudeGeometry

I have a 3D shape (THREE.Shape) that I created in Threejs using some vertices. I then used ExtrudeGeometry to give it a 3D appearance. Now, I need to add a 45-degree cut to the edges of this shape. However, the challenge lies in cutting the edges of the ex ...

Tips for identifying when v8 heap utilization in Node.js is nearing its limit

Currently, my script includes the following code: const v8 = require('v8'); let heap = v8.getHeapStatistics(); let usage = 100 / heap.heap_size_limit * heap.used_heap_size; if (usage > 90) { console.log(`V8 heap usage close to the limit ...

Angular's alternative to jQuery deferred.always() callback

Utilizing the .always() callback function in jQuery allows us to manage responses, regardless of whether they are successful or not. Is there a similar functionality in AngularJS that serves the same purpose? //jQuery $.get( "test.php" ).always(function( ...

What causes these queries to function separately but fail when combined?

I am facing an issue with combining 2 queries in my Firestore collection. These are the 2 examples that work: database .collection('servicebonnen') .where('medewerker', '==', 'CEES') and: database .collecti ...

What methods can be used to block direct attribute updates in a JS/TS class?

class Creature { secretProperty modifySecretProperty(value) { this.secretProperty = value } } new Creature().modifySecretProperty('hidden way') //success new Creature().secretProperty = 'not permitted' // failure To r ...

I am having an issue where my div element is not inheriting the width of its

I am encountering an issue where I have one div and I check the width of that div in jQuery. I then try to set the same width on the next div, but the width does not appear. Can someone please assist me with this? Here is my code: $(document).ready(funct ...

Analyzing and adding Angular JSON information

I'm struggling to understand why the compare function and insert function in my code aren't functioning correctly. I suspect that one reason for this could be that the function is not being called by the button. How can I confirm this? It seems l ...

One way to integrate social sharing buttons into your Django blog

I am currently using the django_social_share module and I am struggling to understand how to send the sharing URL for a specific blog post on social media. Here is my post_detail.html: <article> <div class="embed-responsive embed-responsive-1 ...

Searching for an item within an object to retrieve an alternative element from that very same object

I am currently working on a task that involves checking the data headers to see if they contain 'accept=application/xml', and only then returning the body in XML format. Below is the dataset: [ { url: '/a', status: '200&apos ...

Is Ember CLI experiencing issues due to the latest Ember Data update?

Greetings! I am a beginner with Ember and recently encountered some warnings after upgrading to the latest version of Ember Data: Update: I have two identical versions of my app, one built without ember-cli and the other with ember cli. Both applications ...

Validating a particular value using Regex in React Formik

First, I need to ensure that the field is validated for any characters not included in this set: /[ùûüÿ€’“”«»–àâæçéèêëïîôœ]/. If a user enters a character outside of this set, I want Yup to trigger an error message. Secondly, I ...

Exploring JSON data with jQuery

I'm attempting to extract specific details from a JSON file in Squarespace and then add it to a <div>. The objective is to iterate through the data and retrieve the location information from each post. Below is the code snippet I am currently us ...

Creating a Cubic Bezier Curve connecting two points within a 3D sphere using three.js

I'm currently working on a project where the user can click on two points on a sphere and I want to connect these points with a line along the surface of the sphere, following the great circle path. I have managed to obtain the coordinates of the sele ...

Use jQuery to clear the content within a div element following the removal of an element

A dynamic generation of checkboxes is introduced to div1: $.each(json, function(idx, obj) { $("#tbl1").append('<input type="checkbox" id='+obj.firstId+' onclick=nextPopulate('+obj.firstId+'); >'); } Upon selection, ch ...

Is it possible to access the names of objects within an array in JavaScript?

If objects are created and placed in an array, does the array store only the properties of the objects or also their names? This may seem like a simple question, but I've been unable to find a clear answer. var boxA = {color: "red", width: 100}; var ...

The Javascript/Jquery code executes just once on the initial event, doubles on the subsequent event, and continues to increase in

There is a JS function attached to an HTML button's onclick attribute: function AddFbLikes() { $('#fbform').on('submit', function(e) { e.preventDefault(); // stop form submission $("input:checkbox:checked").each(function(i ...