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

Error message received from GitHub when attempting to create a repository through the REST API states that JSON cannot

I am currently in the process of learning how to use REST APIs for GitHub, and my current project involves creating a new repository using JavaScript. Below is the function I have written for this purpose, which includes generating a token and granting all ...

What is the best way to remove a specific HTML section using a JavaScript function?

I am struggling to figure out how to remove a specific HTML section using a button that is contained within the section itself. The section I want to delete was initially added by clicking a different button. Although I can successfully add a new section ...

Tips for optimizing the sequencing of 3 ajax requests, with the output of one request serving as input for the subsequent two requests

I'm currently working on a solution for chaining 3 ajax calls where the result of one call feeds into the next two. Here's the scenario: // Invoke the ajax calls firstAjax('mypage.gng','john-doe').then(secondAjax, thirdAjax) ...

I encountered a parsing issue while trying to compile my Vue project

Issue: The component name "Header" should always consist of multiple words. Fix: Change the component name to a multi-word format according to Vue standards (vue/multi-word-component-names). ...

Setting Up AdminLTE Using Bower

Recently, I decided to incorporate the Admin LTE Template into my Laravel project. I diligently followed the guidelines outlined here As soon as I entered the command: bower install admin-lte The installation process seemed to start, but then the ...

Setting default values for Vue prop of type "Object"

When setting default values for objects or arrays in Vue components, it is recommended to use a factory function (source). For example: foobar: { type: Object, default() { return {} } } // OR foobar: { type: Object, default: () => ({}) ...

The Eclipse Phonegap framework is experiencing difficulty in loading an external string file with the jquery .load function

A basic index.html file has been created to showcase a text string from the test.txt file by utilizing the .load function from the jQuery library. The goal is to insert the textual content into an HTML (div class="konten"). The provided HTML script looks ...

Solving templateUrl resolution of directives in Angular with RequireJS

Currently, I am using AngularJS and RequireJS in my single-page application (SPA). To organize imports efficiently, I rely on RequireJS. With RequireJS, I can utilize features like baseUrl to resolve import paths seamlessly. Now, I wish to apply the same r ...

Encountering difficulty accessing the object from the props within the created method

After retrieving an object from an API resource and storing it in a property, I encountered an issue where the children components were unable to access the object inside the created method. This prevented me from assigning the values of the object to my d ...

Erasing the content of a text field with the help of a final-form computation tool

I'm attempting to utilize the final-form calculator in order to reset a field whenever another field is modified. In my scenario, there are two fields. Whenever the first field changes, the second field gets reset as expected. However, an issue aris ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Creating an HTML element within a three.js globe

I have a globe created using three.js Reference: I am trying to display an HTML div at a specific latitude/longitude on the globe. Can someone guide me on how to position the div at a particular lat/long? What I've attempted: I'm currently stu ...

What is the best way to incorporate this HTML and script into a React component?

After receiving the embedded HTML and script from a platform, I discovered that a button triggers the script. It was originally designed to be embedded on a website, but I am attempting to integrate it into a React application. Here is the code provided fo ...

What is the correct way to integrate $.deferred with non-observable functions?

Imagine you have two functions filled with random code and the time they take to complete is unknown, depending on the user's system speed. In this scenario, using setTimeout to fire function2 only after function1 finishes is not practical. How can j ...

The sequence of divs in a language that reads from right to left

Is there a way in HTML to designate a set of divs so that they automatically align from left to right for languages that read left to right, and alternatively, flow from right to left for languages that read right to left? This means that the direction of ...

What is the process for defining a global variable within a module in Typescript?

I've already included a global value in my global JavaScript context: const fs = require('fs') For a specific reason, I need to include it in the global scope. Now, I want to create a .d.ts file to declare the global variable with a stron ...

Retrieve information from an express server using the fetch API

I am attempting to use the alert function to display a variable string in Express's .get() method and then send it using res. I want the alert to show "I am working fetch". This is my server.js var express = require('express'); var app = e ...

What is the best way to implement vuelidate when dealing with an array of objects?

In my form questionnaire, I am looping through an array of objects. Each object has five properties, but only one property needs validation. The validation setup in the component looks like this: specificGifts: { $each: { passThrough: { ...

Storing an array within an AngularJS service for better performance

As someone who is relatively new to AngularJS, I am still in the process of understanding how to utilize services for fetching data in my application. My aim here is to find a method to store the output of a $http.get() call that returns a JSON array. In ...

What is the best way to navigate a dynamic table in Vue.js?

I'm currently working on creating dynamic tables in Vue using loops where users can upload a table and view it. <el-table :data="filtered" border style="width: 100%" height="500" @selection-change="handleSelectio ...