JavaScript - convert object to string ( stopped working )

287 views Asked by At

I have javascript object which i need to convert into string.

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

After googling i have got JSON.stringify(obj);

JSON.stringify(obj); is working fine if IE8 modes are same as below

Browser Mode : IE8
Documentn Mode: IE8 Standards

and the same code is not working If

Browser Mode : IE8
Documentn Mode: Quirks Mode

I am wondering why same thing is not working...

any idea will be appreciated.

1

There are 1 answers

0
SK. On BEST ANSWER

I would recommend using JSON.stringify if you can fixed IE modes to IE8 and IE8 standards. JSON.stringify will serializes an object and very easy to use. Most modern browsers support this method natively, but for those that don't, you can include a JS version

and If you can not fixed your IE modes then use below method to convert object to string.

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(',')+'}';
}

Call a function:

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

Output:

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