When JSON contains slashes, JSON.parse will trigger an error

I am struggling with a valid JSON generated using PHP like this:

var json = <?php echo json_encode(['somearray']); ?>
.

Inside the array, there is an HTML string as shown below:

$myArray = ['image' => '<img src="/img/files/icon3.png" alt="" title="" />'];
json_encode($myArray);

However, when I try to parse this JSON using JSON.parser, it keeps throwing an "Unexpected token" error message like this:

"SyntaxError: Unexpected token / in JSON at position XYZ"


For example, consider the following JSON data:

var json = '[{"id":8,"type":"dataFiles","name":"Noise Data Files","selected":{"data":{"id":1,"subscription_id":"3","filestorage_id":"1","title":"test 1","graph_type":"line chart","settings":{"band":"broadband","interval":"long","measurement":"1","time_interval":"","frequency":"","param":"","display":""},"created_at":"2018-07-03 21:46:08","updated_at":"2018-07-03 21:46:08","created_by":"5","page":"1","picture":"customers/3/dataviewer/nKvvMkRbKcU53mkflUdqIe8VUaRrM83EqpsiPNuc.png","pivot":{"project_element_id":"4","dataviewer_id":"1"},"type":"<img src=\"/img/dataviewer/icon.png\" alt=\"3\" title=\"Third\" />","name":"00014_C_110609_240118 (1).csv","instrument":"dBAir","serial_number":"67600","recorded_on":"2024-01-18 11:06:09"}},"set":true},{"id":2,"type":"freeText","name":"Free Text","selected":"Some text","set":true}]';

JSON.parse(json);

Answer №1

The problem you are facing is not related to JSON serialization, but rather how you are pasting it into your code as a string literal.

When a backslash \ is used in a JavaScript string literal within your code, it acts as an escape character. For example, \n represents a newline.

console.log('line 1 \n line 2`);

In this case, trying to escape a forward slash with \/ is unnecessary because the backslash was not escaped properly in the first place. To include JSON directly in your code, you need to double the backslashes to cancel out the escaping of the backslash.

Therefore, \/ should be written as \\/ within your string literal.

This issue can be avoided if you load your JSON data directly from the server instead of pasting it into your code.

Answer №2

When transferring JSON from PHP to JavaScript, I found it necessary to use JSON.stringify(). This process effectively resolved any issues related to special characters like / and other tokens.

Answer №3

*Update: I recently had to reinstall my PHP server for verification purposes, and it seems like there may be an issue with how you're handling the JSON data:

<script> 
  var json = '<?php echo json_encode($myArray); ?>';
  JSON.parse(json);
</script>

It appears that when you use json_encode within HTML directly, there is no need for a subsequent JSON.parse, and you should not treat it as a string. Simply remove the quotes, and your variable var json will actually represent the object itself, not a string. For example:

<script> 
  var myArray = <?php echo json_encode($myArray); ?>;
</script>

Pay attention to the absence of quotes surrounding the <? ... ?>. Additionally, keep in mind that myArray will now be an array, not a string.

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

"Adding properties to objects in a map: a step-by-step guide

During my attempt to add a property within a map loop, I noticed that the update appeared to occur on a duplicate rather than the original object. MY_ARRAY.map(function(d){ d.size = DO_SOMETHING }); ...

Angular JS allows for the display of text from a textarea upon clicking the submit button

Q] How can I display a single text message from a textarea upon clicking the submit button in angular-js? Here is the current code that I have: <html ng-app="myApp"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1 ...

Converting JSON data into a format that can be easily displayed in a

There is this JSON file that my activity fetches and converts into a string: {"popular": {"authors_last_month": [ { "url":"http://activeden.net/user/OXYLUS", "item":"OXYLUS", "sales":"1148", ...

I am struggling to display the data fetched by Next.js on the page

I am struggling to display the data from the first file in my tanstack table or as a string within the HTML, even though I can see it in a console.log when grabbed by axios. The tanstack table worked fine with hardcoded data. In the console image provided, ...

Please indicate the maximum number of digits allowed after the decimal point in the input

My input form uses a comma as the decimal separator: HTML: <form id="myform"> <label for="field">Required, decimal number:</label> <input class="left" id="field" name="field"> <br/> <input type="submit" va ...

Issue: 'node' is not being recognized when attempting to execute the file using the package.json script

Currently diving into the world of Node.js, I encountered an issue stating "node is not recognized as an internal or external command" whenever I attempt to start my project using either npm start or npm run start. Strangely enough, running node index.js ...

Check to see if the event handler is triggered and the promises are executed in sequence (syncronously)

I have a Vue button click handler that, depending on the arguments it receives, can do the following: execute request A only execute request B only execute request A and then request B sequentially (request B is only called if request A completes successf ...

Exclude the initial and final lines from the document in JSON format

Is there a way to have json_decode ignore the first and last lines of a JSON file in order to produce valid JSON output? The contents of my file are as follows: while(true);/* 0; JSON CODE /* */ This is the PHP code I am using: $json = file_get_content ...

When attempting to make an AJAX call using the console, an error was encountered stating that the function $.ajax is not available

Currently experimenting with an ajax call from my console to a local server, but encountering an error: VM4460:1 Uncaught TypeError: $.ajax is not a function(…) Here's the code snippet causing the issue: url = 'http://localhost:8080/testform ...

Steps to set up gapi-script authentication with next-auth in a Next.js application

I have encountered an issue while working on my open-source project that involves utilizing the Google Drive API. Can anyone guide me on how to set up gapi-script authentication using next-auth in a Next.js project? I have managed to implement authentica ...

The contenteditable div's selectAll feature doesn't function properly when it gains focus

I'm working with divs in a table structure and here's an example: <div contenteditable="true" onfocus="document.execCommand('selectAll',false,null)">Something</div> Clicking on a div to focus works perfectly, selectin ...

"Exploring the power of Ajax: a guide to automatically refreshing the response every

I am struggling to understand why this snippet of code isn't working as expected. The div updates when using .html, but not with my custom script. In my setup, I have two files: index.php and test.php The index file looks like this: $(document).rea ...

Utilizing jQuery/Javascript to replicate the data from a table while excluding the header and then pasting it to the

I am attempting to replicate the data from a table while disregarding the header/title row and copying it to the clipboard in the exact same way as manual selection and copy. I came across a post on how to choose Select a complete table with Javascript (t ...

What are some ways to create a versatile wrapper?

I'm currently grappling with an issue involving my Formik fields. I need to utilize FastFields in certain scenarios and Fields in others within my FormikControl, a class designed for constructing formik inputs. The challenge lies in being able to swit ...

The clear icon in React will only appear when there is a value inputted

Is there a way to implement the clear X icon that only appears when typing in the input field using reactjs, similar to the search input on the Google homepage? Check it out here: https://www.google.com import { XIcon } from '@heroicons/react/solid&ap ...

Error: cannot use .json data with `filter` method from WEBPACK_IMPORTED_MODULE_2__["filter"]

There seems to be an error occurring when attempting to retrieve data from a JSON file in the specific line of code selectedEmployee: employeeList.data.Table[0], An issue is arising with TypeError: _employeeList_json__WEBPACK_IMPORTED_MODULE_2__.filter ...

The NodeJS module 'request' is producing symbols instead of expected HTML content

Currently, I am delving into the world of Nodejs and experimenting with web scraping using node.js. My tools of choice are the node modules request and cheerio. However, when I attempt to request a URL, instead of receiving the HTML body, I get strange s ...

The jqGrid fails to display JSON data in the grid properly

Despite the fact that my action method is returning data in JSON format, the jqGrid control seems to have trouble rendering it. Below is the code for the method that returns the data in JSON format: ContactContext db = new ContactContext(); // / ...

Learn the process of merging queries from two tables and grouping them into a JSON Array on a WCF Service

I have two tables in my SQL Server Database and I would like to combine them into a single JSON Array within my WCF Service. Table1: ---------------- | type | total | ---------------- | A | 2 | | B | 3 | | C | 4 | ---------------- T ...

Having issues with your JQuery code?

I am attempting to locate a cell within a table that contains the class 'empty'. My goal is to then utilize a code snippet to obtain the id (cell number) and determine which cells are adjacent to it. As part of my test, I am experimenting with t ...