![](/img/trans.png)
[英]How to convert object to string without JSON.stringify using JavaScript?
[英]How to convert javascript object into json without using “JSON.stringify” method?
有没有办法将javascript对象转换为JSON。
我不能用
JSON.stringify(<obj>)
因为以下链接中的JSON对象中没有stringify方法。
例:
var obj = {'x':1,'y':2}
现在,如果我会跑
console.log(JSON.stringify(obj));
然后我收到了这个错误。
错误:TypeError:对象#没有方法'stringify'
好吧,该网站用自己的方式覆盖了实际的JSON对象。
> JSON
> Object {toStr: function, quote: function}
尝试使用JSON.toStr(object)
似乎某些代码/库已覆盖全局JSON对象。 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})
这是一种适用于因某种原因被覆盖的所有全局对象的技术。 作为替代方案,您始终只能复制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.