Search code examples
jsonangularangular6jqwidget

How to generate specific json with jqwidgets and angular?



I'm trying to export the data of my datatable into a json file.
The table is create with JQwidget on Angular6 and the data come from an API.

But, with the jqwidgets method exportData('json');, only can make a format of a json of the table. [{"id":"1","name":"test"},
{"id":"2","name":"toto"}]

jsonExport(): void {
    this.myDataTable.exportData('json');
  };

I don't know how to change the format of the json to have something like that:
["number":"2",
"1":{"id":"1","name":"test"},
"2":{"id":"2","name":"toto"}]

Thanks


Solution

  • I manage to do what I wanted, it goes like that:
    First, You can't do it with JqWidgets https://www.jqwidgets.com/community/topic/how-to-generate-specific-json-with-exportdatajson-jqwidgets-and-angular/
    Then, my solution is:

  • I created the String inside my Nodejs API as a GET.

    app.get('jsonfile', function (req, res) {
      res.header("Content-Disposition", "attachment;filename=\filename.txt\"");
      connection.query('select * from heroes', function(error, results, fields) {
        if (error) throw error;
        var JSONstring = "[";
          ...
          ...
          ...
        JSONstring = "]";
        res.end(JSONstring);
        console.log(JSONstring);
      });
    });
    

  • res.header('Content-Disposition', 'attachment;filename=\filename.txt\""); is mandatory for my solutio if you want to make this JSON string downloalable as a file.
  • I tried to use this end-point just like the others but I had this problem :

    ERROR 
    Object { headers: {…}, status: 200, statusText: "OK", url: "http://localhost:3000/jsonfile", ok: false, name: "HttpErrorResponse", message: "Http failure during parsing for http://localhost:3000/jsonfile", error: {…} }
    

  • Because it was not working with a button click and ts function.
  • Instead I just made this:

    <a href="http://localhost:3000/jsonfile" ><button>Creation JSON File</button></a>
    

    It works for me, but if there are better solutions, I will be glad to know.

    Thanks all for your help!