简体   繁体   中英

Convert json object into specific format array using angular 5 or javascript

I have a json data that looks like below.

  [{
   {name: "box: 122",x=["2018-01-12T00:01:56.480Z", "2018-01-12T00:05:58.116Z", "2018-01-   12T00:10:00.379Z"], y=[0, 3, 5]},
   {name: "box: 125",x=["2018-01-12T00:01:56.480Z", "2018-01-12T00:05:58.116Z", "2018-01-12T00:10:00.379Z"], y=[1,5,2]}
  }]

Now I want to format this json to below format.

output :

{ 
box: 122,  "2018-01-12T00:01:56.480Z",  0 
box: 122 ,"2018-01-12T00:05:58.116Z" ,  3
box: 122 ,"2018-01-12T00:10:00.379Z",   5
box: 125,  "2018-01-12T00:01:56.480Z",  1
box: 125, "2018-01-12T00:05:58.116Z",   5
box: 125,  "2018-01-12T00:10:00.379Z"   2
}

Basically I will have export this data to csv file.I have tried many code snippet but none of them fulfill desired result. Can anyone help me how to do this in javascript. Thanks in advance.

Few observations :

  • Your JSON is not a valid JSON .
  • JSON does not support = . use : instead of = .
  • valid JSON should be like Array of objects :

    在此处输入图片说明

Solution as per the requirement :

 var jsonObj = [{ "name": "box: 122", "x": ["2018-01-12T00:01:56.480Z", "2018-01-12T00:05:58.116Z", "2018-01-12T00:10:00.379Z"], "y": [0, 3, 5] }, { "name": "box: 125", "x": ["2018-01-12T00:01:56.480Z", "2018-01-12T00:05:58.116Z", "2018-01-12T00:10:00.379Z"], "y": [1, 5, 2] }]; var tableString = "<table>", body = document.getElementsByTagName('body')[0], div = document.createElement('div'); tableString += "<tr><td>name</td><td>x</td><td>y</td><tr>"; for (var i in jsonObj) { tableString += "<tr>"; tableString += "<td>" + jsonObj[i].name + "</td>"; tableString += "<td>" + jsonObj[i].x + "</td>"; tableString += "<td>" + jsonObj[i].y + "</td>"; tableString += "</tr>"; } tableString += "</table>"; div.innerHTML = tableString; body.appendChild(div);
 table, td { border: 1px solid black; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM