JavaScript - changing object into a string (not functioning properly)

Looking to convert a JavaScript object into a string? Here's an example:

var obj = {"name": "XXX", "age": "27"};

After doing some research, I found out about JSON.stringify(obj);

JSON.stringify(obj); works perfectly when the IE8 modes are set as follows:

Browser Mode : IE8
Documentn Mode: IE8 Standards

However, the same code doesn't work if the settings are different:

Browser Mode : IE8
Documentn Mode: Quirks Mode

It's puzzling why it works in one setting but not the other...

If you have any insights, please share!

Answer №1

If you are working with IE8 and IE8 standards, I suggest using the JSON.stringify method to serialize an object. It is a simple and effective way to convert objects into strings. While most modern browsers support this function, for those that do not, you can use a JavaScript version available here.

Alternatively, if you are unable to fix your IE modes, you can utilize the following custom method to achieve the same result:

Custom Function:

function objToString (obj) {
var tabjson=[];
for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
        tabjson.push('"'+p +'"'+ ':' + '"' +obj[p] + '"');
    }
}  tabjson.push()
return '{'+tabjson.join(',')+'}';
}

Usage of Custom Function:

var obj = {"name": "XXX", "age": "27"};
objToString(obj );

Output:

"{"name":"XXX","age":"27"}"

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

Unable to use .click function to choose image within container

Apologies for the lengthy post, but I believe providing all details is essential to understanding the issue at hand. The following code snippet is intended to display the first image in a pop-up box when a user clicks on any of the images shown: <div ...

Converting counterup2 to pure vanilla JavaScript: step-by-step guide

Is there a way to convert the counterUp2 jQuery code to vanilla JavaScript? const counters = document.querySelectorAll('.counter'); function count(element) { let currentValue = 0; const targetValue = parseInt(element.innerText); let interv ...

Sending an ArrayBuffer from Angular to Electron results in the window crashing

In my Electron application, I have integrated an Angular application internally. I am trying to download a byte array (ArrayBuffer) via an API call and then passing this data to a method connected through electron.remote.require('./file-service') ...

Extracting information from JSON structure

My JSON object response includes a `series` array of objects structured like this: { series: [ { name: 'a', data: [1,2,3] }, { name: 'b', data: [4,5,6] } ] } I am looking to extract the `data` values th ...

"Encountering a hang while using the .save() function and only

Issue with storing data in MongoDB This is only my second attempt at saving data to a database and I am still relatively new to the process. I have a form on my HTML page that sends string data to be saved in a MongoDB database. I successfully connected t ...

Discovering the number of words, extracting specific words, and transferring them to a URL using JavaScript

I have retrieved a document from a URL and saved the response. There are 3 tasks I need to accomplish here:- Calculate the word count in the document. Gather information for the top 3 words (sorted by frequency) including synonyms and parts of speech. A ...

How can a string be formatted based on a dictionary or JSON object in Python?

I am facing an issue with a JSON file that I have converted to a Dict. The dict looks something like this: { "a": "1", "b": "2", "c": "3" } Now, I need to format a string based on the values ...

In the event that the "li" element contains an "

<ul> <li> <ul></ul> </li> <li></li> <li></li> <li></li> <li> <ul></ul> </li> </ul> Is there a way to specifically a ...

Implementing role-based authentication in Next.js using Next-auth and Firebase

Currently, I'm in the process of integrating role-based authentication using NextAuth.js into my Next.js application. Despite following the provided documentation meticulously, an error (in profile snippet and callback snippet which I copied from next ...

Attempting to conditionally map an array of objects

I am currently working on conditionally rendering content on a screen. My main task involves manipulating an array of 3 objects with sub-objects, stored as the initial state in my reducer (using dummy data). The layout includes a customized SideNav bar wit ...

Using jQuery to modify an array based on information stored in a cookie

I am attempting to extract an array from a stored cookie. Within this cookie, the following array code is saved. What would be the most effective method of retrieving the value from the cookie? I aim to utilize the value within the array and believe tha ...

The destroySlider() function of BxSlider fails to work due to either an undefined slider or a function that is not

I'm facing an issue with my carousel setup using bxslider. Here is the code snippet responsible for initializing the carousel: jQuery(document).ready(function() { var carouselWidth = 640; var carousel; var carousel_Config = { minSlides: 1, ...

React: The 'Redirect' function is not included in the export list of 'react-router-dom'

When I try to run npm run start in the terminal, an error message appears. 'Redirect' is not exported from 'react-router-dom', causing an import error. I have attempted various solutions like reinstalling node_modules, react-router-d ...

A numeric input area that only accepts decimal numbers, with the ability to delete and use the back

I have successfully implemented a code for decimal numbers with only two digits after the decimal point. Now, I am looking to enhance the code in the following ways: Allow users to use backspace and delete keys. Create a dynamic code that does not rely o ...

What is the best way to retrieve specific JSON data from an array in JavaScript using jQuery, especially when the property is

Forgive me if this question seems basic, I am new to learning javascript. I am currently working on a school project that involves using the holiday API. When querying with just the country and year, the JSON data I receive looks like the example below. ...

What is the most efficient method for retrieving information from this JSON using PHP?

[{"id":"1",name":"Title One","players":"999"},{"id":"2","name":"Title Two","players":"100"}] What is the best way to display this information? ...

Using a template literal as a prop is causing rendering issues

I have a functional component const CustomParagraph = forwardRef((ref: any) => { return ( <div> <p dangerouslySetInnerHTML={{ __html: props.text }}></p> </div> ); }); Whenever I use this component, I am unable ...

Ajax updates previous text to new text upon successfully completing the task

I have a question regarding changing text using AJAX after success. I have written this AJAX code which is functioning properly. However, I aim to replace the old text with new text in the .chnged div. For instance: <input type="text" name="text" va ...

Polymer custom components and Polymer motion recognition techniques

Looking to implement a listener event on a Polymer custom element using Polymer-gestures. Here is a snippet of my code: - my-custom-element.html <link rel="import" href="../polymer/polymer.html"> <polymer-element name="my-custom-element" attri ...

Can I restrict access to all routes except one in vue-router? Is this a safe practice? Should I explore alternative methods for achieving this?

I am looking to create an online exam consisting of 5 pages, each with a countdown timer set at 120 seconds and 4 questions on each page. Once the timer runs out, users will be automatically redirected to the next page, or they can manually click the "next ...