Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert javascript object into json without using "JSON.stringify" method?

Is there any way to convert javascript object into JSON.

I can not use

JSON.stringify(<obj>)

Because there is no stringify method in the JSON object in the following link.

Link

Example:

var obj = {'x':1,'y':2}

Now if I'll run

console.log(JSON.stringify(obj));

Then I'm getting this error.

error: TypeError: Object # has no method 'stringify'

like image 319
Dixit Singla Avatar asked Mar 25 '14 08:03

Dixit Singla


3 Answers

Well, the website overrides the actual JSON object with their own.

> JSON
> Object {toStr: function, quote: function}

Try using JSON.toStr(object)

like image 157
Umur Kontacı Avatar answered Oct 29 '22 16:10

Umur Kontacı


It appears that some code/library has overridden the global JSON object. JSON.toStr is fine but if you want the original JSON objet back you can always create an invisible frame and use its global objects

OriginalJSON = (function() {
  var e = document.createElement('frame');
  e.style.display = 'none';
  var f = document.body.appendChild(e);
  return f.contentWindow.JSON;
})()

OriginalJSON.stringify({a: 1})

This is a technique that works for all global objects that has been overridden for some reason. As an alternative you can always copy only the stringify method

JSON.stringify = (function() {
  var e = document.createElement('frame');
  e.style.display = 'none';
  var f = document.body.appendChild(e);
  return f.contentWindow.JSON.stringify;
})()

// Now JSON.stringify is back
JSON.stringify({a: 1})
like image 25
Gabriele Lana Avatar answered Oct 29 '22 15:10

Gabriele Lana


stringify method depends on your browser.

So if you cannot find JSON.stringify(), maybe the browser you're using is not compatible to JSON API, you could include this library to make it there:

json2.js

like image 40
Colin Su Avatar answered Oct 29 '22 17:10

Colin Su