![](/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.