Is there a discrepancy in the JSON algorithm?

While using google chrome, I encountered the following scenario:

I had an object in javascript that looked like this:

var b = {
    text: 'hello world, you "cool"'
};

I then used JSON.stringify to convert it to a string and sent it to the database. In the database, it appeared as:

{"text":"hello world, you \"cool\""}

Upon retrieving it from the database on the server and attempting to send it back to JavaScript by parsing it, I experienced an issue. Even though it was a valid JSON string, passing it to JavaScript through server scripting language like this caused an error:

"javascript:loadText(' + str + ')"...

The loadText function is a JavaScript function:

function loadText(val) {

   console.log(JSON.parse(val));
}

This resulted in an error. However, when trying another approach in JavaScript alone without encountering the error:

var b = {
    text: 'hello world, you "cool"'
};

console.log(JSON.parse(JSON.stringify(b)));

Could this be due to the JSON stringify/parse algorithm?

PS:

This alternative method also proved to be problematic:

loadText('{"text":"hello world, you \"cool\""}');

Answer №1

The code snippet

"javascript:loadText(' + str + ')"
you have written is actually trying to pass the text + str + as an argument to the function loadText.

To correct this issue, you can either adjust your quotation usage or modify the code to indirectly include the single quotes:

javascript:loadText(String.fromCharCode(39) + str + String.fromCharCode(39))

Answer №2

When troubleshooting JavaScript errors, avoid focusing on server-side code.

Instead, examine the JavaScript code being generated.

"javascript:loadText(' + str + ')"

This will result in something similar to:

"javascript:loadText({"text":"hello world, you \"cool\""})"

Therefore, it is essential to enclose the data in quotes and escape any special characters to maintain its JSON format when inserting into JS.

Furthermore, considering the context, it is advisable to encode the data for URL compatibility as well.

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

Stop the HTML5 video playback within a slider (flickity)

As I add slides to a slider using flickity, I am encountering an issue where the first video pauses when there is a slide change event. However, if I play the video on the next slide and then move back or forward, the video does not pause. This is my curr ...

Storage in private Safari mode is not synced between tabs on mobile devices

In the private mode of mobile Safari, I have successfully stored data in the localStorage. However, when I open my web app in two separate tabs, I notice that the data stored in one tab is not accessible in the other tab. This behavior may be present in ot ...

Building a dynamic form in React: Fetching select data from an API, posting to another API, and automatically clearing fields upon submission

I am currently working on a form that utilizes a GET request to retrieve data from an API endpoint and then proceeds to make a POST request to another endpoint. Although I have been successful in achieving this function, I am facing challenges with reset ...

What are the best practices for managing POST data in Express.js?

Lately, I've been consistently encountering 500 errors from Express.js which seem to stem from a failure to retrieve a crucial string key required by the request. On the client side, numerous requests are being made to the same endpoint (/restore), a ...

How can I utilize Axios in Vue.js to access a local JSON file?

I'm trying to figure out how to read a local JSON file using Axios. The data.json file is located in public/info/data.json. However, every time I attempt to make a get request, I receive a 404 error message. Here is the content of data.json: [ {" ...

Dynamic Selection of JSON Key-Value Pairs in React Framework

My json data structure resembles the following: { "index": 1, "ln": "27953", "name": "Product 1", "availability": { "day0726": "G", "day0727": "G", "day0728": "G", } } I am looking for a way to dynamically disp ...

phpUsing a foreach loop to iterate through an associative array and

I have a database table in Microsoft Access with three fields: partno, description, and quantity. However, when I try to retrieve the data and display it in an HTML table, I encounter an error message. An issue occurred while trying to access the ' ...

Find the two numbers within a specific range in an array using jQuery

I have two arrays and I need to check for any duplicate ranges. How can I achieve this? let startingArray = ['1', '6.1', '10', '31','6.2',3]; let endingArray = ['2', '9.9', '30&ap ...

Tips for Incorporating the YouTube Iframe API into Your ReactJS Project

While working in React, I am attempting to build a custom YouTube player component that includes a new set of player controls. The YouTube iframe API provides the following code snippet for creating a player instance: var tag = document.createElement(&ap ...

Using ASHX to Return JSON in ASP.NET

I have implemented autocomplete functionality on my website. The JavaScript part is complete and I am able to retrieve the MembershipUser object of the matching user. Now, I need to format the JSON response as follows: { query:'Li', suggestio ...

How can I retrieve an SQL query result in JSON format using Ajax?

Similar Question: JSON encode MySQL results In this scenario, the use of Mysql fetch array method is employed to showcase the output. The question that arises here is how one can replace these tags by utilizing JSON encoding. Attempting to retrieve a ...

How is it that when a function is called with just one parameter, it ends up receiving the entire element?

In my table, I have various item numbers listed with corresponding quantity input fields identified by id="itemNumber". Each line also includes a button that triggers a function (onclick="addItemAndQuantity(itemNumber)") to retrieve inf ...

Javascript - Incorporate a hyperlink into my Flickr Api image query

I am struggling with incorporating a link around the image generated by this request due to my limited API knowledge. Below is the current function responsible for displaying the album images. To see a functional version, please refer to the provided fidd ...

How to use jQuery to update the href attribute of a parent link

Can someone help me figure out why I am having trouble changing the 'href' of the parent link to a header logo? Thank you in advance! Here is the HTML code snippet: <a href="https://URL.IWANTO.CHANGE"> <img id="partner_logo" src="/ ...

What is the best way to store textarea information into a session using the jQuery AJAX post method in Codeigniter?

I am having trouble saving the text from a textarea to the Controller session using jQuery AJAX post method in Codeigniter Smarty. I am unable to save the data to the session. Can someone please provide me with guidance and a detailed example of how to ach ...

What methods can be employed to utilize a JSON URL request in order to define numerous values for a singular parameter?

Working with a JSON API involves sending requests through URL's in the browser to retrieve information. In this case, I am retrieving data about football matches from an Endpoint that has a parameter called league_id which specifies information relate ...

What is the best way to validate if fields are blank before sending a message using the button?

<template> <div> <div class="form-group"> <label for="name">First Name</label> <input type="text" class="form-control" v-model="firstName" placeholder="Ente ...

.value not showing correct data in JavaScript

I am attempting to retrieve the value entered by the user in an HTML input field. While I can display a fixed, predetermined value with ease, this is not my intention. My goal is for users to input a numerical value and for that value to be displayed/adj ...

In Vue, the concept of using the debounce method is not clearly defined

I am aware that using the arrow syntax for a method can cause 'this' to not be mapped to the Vue instance. In my case, I am utilizing lodash.debounce and I don't think I'm using the arrow syntax here? Encountering Error: Cannot read pr ...

Using Python to validate JSON keys and values

I'm currently working on developing a Python code that takes a JSON file as input. This JSON file can contain various data structures such as dictionaries and lists. The main goal of my program is to print out the keys present in the JSON file. Howeve ...