[英]How to convert javascript object into json without using “JSON.stringify” method?
Is there any way to convert javascript object into JSON. 有没有办法将javascript对象转换为JSON。
I can not use 我不能用
JSON.stringify(<obj>)
Because there is no stringify method in the JSON object in the following link. 因为以下链接中的JSON对象中没有stringify方法。
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'
错误:TypeError:对象#没有方法'stringify'
Well, the website overrides the actual JSON object with their own. 好吧,该网站用自己的方式覆盖了实际的JSON对象。
> JSON
> Object {toStr: function, quote: function}
Try using JSON.toStr(object)
尝试使用
JSON.toStr(object)
It appears that some code/library has overridden the global JSON object. 似乎某些代码/库已覆盖全局JSON对象。
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 JSON.toStr
很好但如果你想要原来的JSON
对象,你总是可以创建一个不可见的框架并使用它的全局对象
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 作为替代方案,您始终只能复制
stringify
方法
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})
考虑使用外部库,例如JSON 3是一个不错的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.