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);
}
有人可以幫我請
如何是作爲屬性值分配之前,首先字符串化數組'數據按鈕'填充在第一位? – Hydrothermal
'[object Object]'不是JSON。這是對隨機對象的'toString()'調用的結果,但它顯然不能轉換回實際的對象。你怎麼真的以這個屬性的價值結束了,你究竟在做什麼? – jcaron
當最初生成錨標記時,您需要解析'JS對象',否則對象數據顯示爲'[object Object]' – Derek