When attempting to parse a single string stored in a cookie with JSON.parse, it results in a "SyntaxError: Unexpected Number" error being thrown

I am facing an issue with parsing a string stored in a cookie.

"d967fac49ef2466239168bbbde0a8d755a27ba81$[[\"__json_message\"\05425\054\"This is a message.\"]]"

Also known as

"\"d967fac49ef2466239168bbbde0a8d755a27ba81$[[\\\"__json_message\\\"\\05425\\054\\\"This is a message.\\\"]]\""

(to be used in console)

Although I cannot parse it using JSON.parse and resort to eval, which poses security risks. The error message states SyntaxError: Unexpected number.

The presence of escaped commas is noteworthy, indicating that this was generated utilizing the Django messaging API.

Can anyone suggest a suitable regex or alternative method to resolve this?

The initial step involves unescaping the string (as it is a valid JavaScript string) followed by obtaining the array after the dollar sign (s.substring(s.indexOf("$")+1)).

Answer №1

Apologies for any confusion earlier, but I have managed to resolve it thanks to the helpful link provided by jfriend00 to json.org. Below is a modified string that now works correctly and displays the intended output. It involves unescaping a JSON array within an already encoded string.

var s = JSON.parse("\"d967fac49ef2466239168bbbde0a8d755a27ba81$[[\\\"__json_message\\\"\\u002C25\\u002C\\\"This is a message.\\\"]]\"")
// s = "d967fac49ef2466239168bbbde0a8d755a27ba81$[["__json_message",25,"This is a message."]]"
// Correct output achieved
var a = JSON.parse(s.substring(s.indexOf("$")+1))

The issue stemmed from converting commas to octal escape codes in the string preparation for the cookie, which is not allowed in JSON formatting. The related error message should have been JSON forbids octal prefixes. Once this is rectified by replacing octal with hex escape codes, it will function properly. Therefore, I will implement a check for octal escapes and substitute them with hex equivalents.


TL;DR: "SyntaxError: Unexpected Number" equates to "SyntaxError: JSON forbids octal prefixes"


Below is the function I employed

var s = "\"d967fac49ef2466239168bbbde0a8d755a27ba81$[[\\\"__json_message\\\"\\05425\\054\\\"This is a message.\\\"]]\"""
var re = /\\0([0-7]{2})/g
JSON.parse(s.replace(re, function(m, n){return "\\x"+("0000"+parseInt(n,8).toString(16)).slice(-4)}))

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

Dynamically adding a class to the initial set of elements in a React map function

In my current project, I have a specific requirement where I need to assign a class to the first n elements of an array. These first n elements are obtained from the parent component and their count increases gradually. One approach that I considered was ...

The Role of AI in Gaming

I am currently developing a car racing game using THREE.js. I am inquiring about how to incorporate Artificial Intelligence into the enemy cars so that they can actively search for and target the player. Can you provide insight into the algorithms typica ...

Executing a JavaScript function using document.write()

When I try to click on the SWF part1 links within the document.write() function in order to call the openswf function, nothing happens. Here is my code: <html> <a href="#" onclick="Popup();">show popup</a> <script> functio ...

md-input container displays content only upon user interaction

Currently, I am working with AngularJs 1 and Angular-Material Design. One issue I encountered was with a md-input container used for file uploading. The problem I faced was that even after selecting a file, it wasn't being displayed in the md-input co ...

When altering the initially loaded app in Django, the framework fails to search in the correct template directory

In my Django project, I have created two apps called file-management and docs. Initially, when I created the file management app, my base urls.py looked like this: from django.contrib import admin from django.urls import include, path urlpatterns = [ ...

Obtain the identifier for a single button within a collection of buttons in an HTML form using Django

I've incorporated Django as the framework for a tracking platform, utilizing it as an FSM. At this juncture, I aim to enable users to modify the machine's state. The state is denoted by a django-fsm field, essentially a CharField integrated with ...

Updating choices within a div in real-time by changing the select box dynamically

I need to swap out the select box that is nested inside this div <div class="models"> <select disabled="disable"> <option>Model Name</option> </select> </div> I am attempting to target the div and manipul ...

What are the capabilities of Ajax when it comes to utilizing select controls in J

Is there a way to trigger an ajax call when a select control value is clicked? The onChange event doesn't seem to work for me in this case :( This is what I have tried so far: JAVASCRIPT: <script> function swapContent(cv) { $("#myDiv"). ...

Is Apollo Client in NextJS failing to refresh data post mutation?

On this page, you can create a new User const [createType, { loading, data }] = useMutation(CREATE_USER_CLASS) //mutation query const createUserClass = async (event) => { event.preventDefault(); try { const { data } = await createType({ ...

Acquiring XML data directly in jQuery without any preprocessing

Hey there, I'm dealing with an unusual situation. I need to extract data from an API that returns malformed XML. Each <episode> in the response has its own <title> tag. However, when using $.get or $.ajax, all these titles end up in the &l ...

Module for React Native that enables users to select and copy text within a specified view

Is there a feature that enables users to highlight and copy text from within a view? If not, is there a method to identify all "Text" type elements and extract the text they contain? <View> <Text>Text1</Text> <Text>Text2</Text& ...

Is it possible to dynamically modify the fetch URL for getServerSideProps using an onClick event?

I'm struggling to find a solution to changing the fetch URL. Specifically, I want to update my let page and refresh getServerSideProps to re-render all News by clicking a button. Is there a way to accomplish this, or should I explore alternative metho ...

Tips on sending an Ajax POST request to execute a PHP file

//The code below is found in the inserirPF.js file function add(){ var method = 'AddPerson'; $.ajax({ url: "../class/dao/InserirPFDao.class.php", type: 'POST', data: {Method:method, NAME_:NAME, EMAIL_:EMAIL, PASS ...

Angular 7 - Issue with rendering only the "dist" folder on the browser, not the "src" folder when using nodejs

Greetings! I'm embarking on a new project involving a nodejs app with angular7. Below is the content of my mail server.js file in nodejs: var express = require('express'); var mysql = require('mysql'); var bodyParser = require(&a ...

Using ReactJs to show a particular piece of information from an object within an array by clicking

My data consists of an array filled with objects, each of which includes an ID, title, job description, and salary. This data is stored in a separate file as shown below: export const CareerList = [ { id: 1, title: "Junior Accountant", sala ...

Exploring the Unchanging Object3D Characteristics of ThreeJS Version 68

According to the transition notes from r67 to r68, it is stated that: Object3D's position, rotation, quaternion and scale properties are now immutable. How does this impact practical implementation? I am seeking further clarification on this matte ...

Issues encountered with rest arguments while setting up gtag

I am currently working on implementing a Google Tag loading script using TypeScript. const GTAG_ID = 'ID'; const script = document.createElement('script'); script.src = `https://www.googletagmanager.com/gtag/js?id=${GTAG_ID}`; ...

Utilize a PHP script to scan and upload PDF files seamlessly

Is there a way to upload PDF files after scanning them using a scanner feeder? Currently, I am utilizing the OCX plugin for uploading images to the server. However, in the application I am developing, I need to upload PDF documents instead. Can anyone re ...

What is the method for evaluating two variables in Javascript?

In attempting to compare two distinct variables, userInput and commandOne, I aim to trigger specific code upon a match between them. The initial step involves pressing a button to activate myTest(). function myTest() { userInput = document.getElementB ...

Check for an Ajax request when there is no cached data present

As a newcomer to JavaScript/jQuery, I have encountered what seems like a fairly solvable issue. The task at hand is to cache a variable (list) in a session, and if the list has not been cached previously, an ajax request should be triggered. However, my p ...