PHP encountering a bad escaped character while parsing JSON using JSON.parse

I'm encountering an issue with JSON parsing. In my PHP code, I have the following:

 json_encode(getTeams(),JSON_HEX_APOS);

This returns a large amount of data.

Sample data: To provide more clarity, let's assume I have this:

my_encoded_data = 
     {
        "13": "Germany-1",
        ...
        "68": "C. Oberstolz/P. Gruber"
    }

To validate the data, I split it into smaller parts and checked it using JSONLint, where it was confirmed as valid JSON. Next, I assigned it in JavaScript like so:

window.objteamsFromServer  = my_encoded_data;

Then, when attempting to parse it in JSON:

arrSearch = window.objteamsFromServer;

It throws this error:

JSON.parse: bad escaped character 

How can I resolve this issue?

Please let me know if any additional information is required.

Thank you,
Awlad

Answer №1

It seems like you might be having trouble understanding what exactly my_encoded_data represents based on your question. It sounds like you are taking the output of json_encode and using it within JavaScript source code, such as:

window.objteamsFromServer = {
    "13": "Germany-1",
    "14": "Russia-1",
    "15": "Switzerland-1",
    "16": "Canada-1",
    "17": "USA-1",
    // ...and so forth
};

Additionally, it seems like you are attempting to parse this data again using JSON.parse.

However, this is not necessary. The JavaScript engine will have already interpreted the object initializer (as it is JavaScript source code, not JSON), so you can access the values directly like this:

console.log(window.objteamsFromServer[13]); // "Germany-1"

Answer №2

It seems that the error you're experiencing might be related to this specific line:

"43": "A. Florschütz/T. Wustlich",

Take note of the special character 'ü' in the name mentioned above.

One potential solution is to encode the data on the server side and then decode it on the client side. You can use JavaScript's decodeURIComponent function for decoding on the client side.

To learn more about server-side encoding of data, you can refer to the PHP documentation.

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

The Express application encounters a 500 Internal Server Error due to a TypeError where the Object #<EventEmitter> does not contain the method 'hr

The staging instance of my webapp is encountering an issue: Express 500 TypeError: Object #<EventEmitter> has no method 'hrtime' at Object.logger [as handle] (F:\approot\node_modules\express\node_modules\connect ...

Tips for resolving an issue with mongoose Model.create becoming unresponsive indefinitely

I'm having trouble understanding why my mongoose Model.create operation isn't completing successfully. The same connection is working well with other controller functions. vscode postman I am attempting to create a new document, but my code s ...

Performance issues when fetching data from ASP.NET Core 6 Web API controller

In our ASP.NET Core 6 Web API project using C#, we encountered an interesting issue after upgrading from ASP.NET Core 3.1. The problem lies in the performance of certain APIs that utilize: return new JsonResult(data) This operation is unusually slow, taki ...

There is an error message in Vue nextTick: "TypeError: this.method is not a function." The error only appears in my console, but the functionality seems to be working correctly in the browser

I'm experiencing an issue where I encounter an error when accessing a certain component for the second time in my browser. The strange thing is that everything appears to be working fine initially, but the error occurs when I try to perform actions li ...

Disregard any labels when it comes to clickable areas for mouse events

Here is a simple example in JSFiddle where a text is displayed over an image inside a div element. Depending on where the cursor hovers, it can exhibit three different behaviors: pointing hand over the image, allowing text selection over the content of the ...

Encountering sporadic EACCES issues while executing selenium tests in the AVA framework

Encountering errors on Windows 10 1809 while using Chrome for testing purposes. Error message 1 Frequency: Occurs approximately every 50th driver instantiation. [...]project\node_modules\selenium-webdriver\net\portprober.js:159 ...

PHP cannot reference a colon within an XML tag

I am looking for a solution to handle the colon in this specific XML structure, whether it's replaced or integrated. This particular tag is nested within multiple other tags, and here is the problematic XML snippet: <ns2:Amount>9.99</ns2:Amo ...

Error in MEAN CRUD operation cannot be determined

{ text: undefined, done: false, _id: 529e16025f5222dc36000002, __v: 0 } PUT /api/todos/529e16025f5222dc36000002 200 142ms - 68b Encountering an issue while updating my CRUD todo list. Despite receiving a successful status code of 200 after submittin ...

When collapsing an accordion, Bootstrap radio buttons fail to properly select

I have attempted various methods to achieve the desired functionality of having the accordion content close and open accordingly when checking a radio button, while also having the button visually appear as 'checked'. For a more in-depth example, ...

Using JavaScript to Retrieve, Manipulate, and Merge JSON Data from Various Files

My knowledge of JavaScript is limited, but I am interested in uploading multiple JSON files, processing them, converting them to text, combining them, and downloading them into a single JS file. I have successfully achieved this for a single file, but I a ...

Styled-components is not recognizing the prop `isActive` on a DOM element in React

In my code, I have an svg component that accepts props like so: import React from 'react'; export default (props) => ( <svg {...props}> <path d="M11.5 16.45l6.364-6.364" fillRule="evenodd" /> </svg> ) ...

Creating a single object from an array using Zend_Soap_Client

I'm currently facing an issue with Zend_Soap_Client while working on my project: <parent> <child><name>abc</name></child> <child><name>def</name></child> </parent> When there are mu ...

LiveValidation plugin causing issue with removing dynamically inserted elements

My form validation is powered by the Live Validation plugin. After submission, the plugin automatically inserts a line of code like this one: <span class=" LV_validation_message LV_valid">Ok</span> However, I encountered an issue when trying ...

Building module dependencies in the Dojo dojo

I'm in the process of utilizing the Dojo builder to compile a unified file that encompasses all the necessary modules for my application, excluding the application itself. Below is an illustration of a layer definition: layers: { 'dojo/dojo ...

When transmitting a base64 image to the server using an AJAX POST request, the forward slashes ("/") are being replaced by ampersands ("%")

I need to send an image as base64 to the server. This is how I am making the request: $.post(Config.serviceURL('captureImage/' + memid), { imageString: imageData }, function(data) { alert("Image uploaded!", data); }).fail(function() { ...

Scheduling a cron job to run at a particular date and time

Our express js application includes a feature in the admin module where users can send emails at specific dates and times they select. For example, if the chosen date and time is [email protected], we need to execute the email code at that exact time ...

In the Vercel production environment, when building Next.js getStaticPaths with URL parameters, the slashes are represented as %

I've encountered an issue while implementing a nextjs dynamic route for my static documentation page. Everything works perfectly in my local environment, and the code compiles successfully. However, when I try to access the production URL, it doesn&ap ...

"Implementing a dynamic way to assign values to different item types in React

There is an object with multiple values inside: const [sort, setSort] = useState({ "city": [], "price": [], "year": [] }); When the "add" button is clicked, the "city" value should be updated to include certain va ...

Which property is best suited for styling a phone number field in the MUI data grid in ReactJS?

I previously utilized the pattern attribute for input fields in pure HTML, but now I no longer have any input fields. What should be my next steps? Can you provide me with a reference in the MUI documentation? https://i.stack.imgur.com/ ...

Maintaining data after page reload in Angular

angular.module('eventTracker', []) .controller('MainCtrl', ['$scope', 'Event', function($scope, Event){ $scope.eventData = {} $scope.onSubmit = function(){ Event.Add($scope.eventData) $scope. ...