2016-09-25 57 views
2

我有一個標籤至極包含這樣一個數據對象:解析andstringify JSON對象的jQuery

<a class="export-json" data-button="[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]">Export json</a> 

這些值數據,鍵傳遞這樣的:

$(".export-json").attr("data-button", data); 

data是一個列表其中包含json

數據是這樣的:

[{ 
name: "John", 
position: "663", 
a: 15, 
b: 48 
}, 
{ 
name: "311", 
position: "663", 
a: 12, 
b: 48 
}] 

所以我要轉換的數據對象和下載爲JSON文件。

$(".export-json").click(function(){ 
     var data = $.parseJSON($(this).attr('data-button')); 
     exportJson(this, data); 
    }); 

function exportJson(element, data) { 
    var results = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data)); 
    element.setAttribute("href", "data:"+results); 
    element.setAttribute("download", "data.json"); 
} 

如果我不喜歡這一點,因爲這parseJSON這裏$.parseJSON($(this).attr('data-button'))我得到:

Uncaught SyntaxError: Unexpected token o in JSON at position 1 

如果我刪除parseJSON,當我下載的文件,我有這樣的:

"[object Object],[object Object],[object Object],[object Object],[object Object]" 

我不知道爲什麼會發生這種情況?

如果我去通過數據都被corectly印刷:

for (var i = 0; i < data.length; i++) { 
    var item = data[i]; 
    console.log(item); 
} 

有人可以幫我請

+1

如何是作爲屬性值分配之前,首先字符串化數組'數據按鈕'填充在第一位? – Hydrothermal

+0

'[object Object]'不是JSON。這是對隨機對象的'toString()'調用的結果,但它顯然不能轉換回實際的對象。你怎麼真的以這個屬性的價值結束了,你究竟在做什麼? – jcaron

+0

當最初生成錨標記時,您需要解析'JS對象',否則對象數據顯示爲'[object Object]' – Derek

回答

1

使用jQuery data()方法,而不是attr()

變化:

$(".export-json").attr("data-button", data) 

收件人:

$(".export-json").data("button", data) 

然後,它會被存儲爲數組,不需要任何解析

如果你真的需要這一個屬性,你將需要