Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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'

share|improve this question
    
No repo, jsfiddle.net/nXQxC –  Praveen Mar 25 at 8:48
    
Fiddle works fine in Chrome –  Starscream1984 Mar 25 at 8:53

4 Answers 4

up vote 1 down vote accepted

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

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

Try using JSON.toStr(object)

share|improve this answer
    
Thanks Man. You are observant! –  Dixit Singla Mar 25 at 9:00

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

share|improve this answer
    
Browser supports because I can use it in other sites! –  Dixit Singla Mar 25 at 8:51
    
if so include that library solves your problem too. –  Colin Su Mar 25 at 8:52
    
But I'm curious about your situation, could you provide any sample to see why only your site JSON got blocked? –  Colin Su Mar 25 at 8:52

Consider using external library, for example JSON 3 is a good choice.

share|improve this answer

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})
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.