解析和字符串化json对象jquery

parse andstringify a json object jquery

本文关键字:json 对象 jquery 字符串      更新时间:2023-09-26

我有一个包含如下数据对象的标签:

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

这些值像这样传递给data-button:

$(".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]"

我不知道为什么会这样?

如果我遍历数据,所有内容都打印正确:

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

有人能帮我一下吗

使用jQuery的data()方法代替attr()

改变:

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

:

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

然后它将被存储为数组,不需要任何解析

如果你真的需要这个属性,你需要先将数组字符串化,然后再分配属性值