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