javascriptjqueryjsonparsing

parse and stringify a JSON object jQuery


I have a tag which contains a data object like this:

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

Those values are passed on data-button like this:

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

data is a list which contains json.

data is like this:

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

So I want to convert that data object and download it as a JSON file.

$(".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");
}

If I do like this because of this parseJSON here $.parseJSON($(this).attr('data-button')) I get:

Uncaught SyntaxError: Unexpected token o in JSON at position 1

If I remove the parseJSON, when I download the file I have this:

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

I don't know why this is happening?

If I go through data everything is printed correctly:

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

Can somebody help me please?


Solution

  • Use jQuery data() method instead of attr()

    Change:

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

    To:

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

    Then it will be stored as array and won't require any parsing

    If you really needed this in an attribute you would need to first stringify the array before assigning as attribute value