数据未完全从JSON转换为CSV。

huangapple go评论74阅读模式
英文:

Data not completely convert from JSON to CSV

问题

以下是翻译好的部分:

我有一组如下所示的JSON格式。在从JSON转换为CSV时,函数可以工作,但并不是所有的“key”都存在于CSV文件中。如何使CSV文件中的所有“key”都可用?

参考:如何将JSON转换为CSV格式并存储在变量中

JSON

var data = {
  "items": [
    {
      "bandwidth": "",
      "destination_ipv4": "",
      "destination_ipv6": ""
    },
    {
      "interface": "",
      "alarm": false,
      "service": [

      ]
    },
    {
      "unit": {
        "name": "operation",
        "shaping-rate": {
          "rate": "1G"
        }
      },
      "ipv6_address": ""
    },
    {
      "vrf": ""
    }
  ]
};

当前结果
数据未完全从JSON转换为CSV。

期望结果
数据未完全从JSON转换为CSV。

JS

function download_file(data) {
    const items = data.items;
    const replacer = (key, value) => value === null ? '' : value;
    const header = Object.keys(items[0]);
    let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
    csv.unshift(header.join(','));
    csv = csv.join('\r\n');

    var link = document.createElement("a");
    link.id = "lnkDwnldLnk";
    document.body.appendChild(link);
    blob = new Blob([csv], { type: 'text/csv' });
    var csvUrl = window.webkitURL.createObjectURL(blob);
    var filename = 'Result.csv';
    jQuery("#lnkDwnldLnk")
    .attr({
        'download': filename,
        'href': csvUrl
    });
    jQuery('#lnkDwnldLnk')[0].click();
    document.body.removeChild(link);
}

请注意,图片描述和链接无法提供翻译。

英文:

I have a set of JSON format as below. During converting from JSON to CSV, the function is worked but not all key is exist in the CSV file. How to allow all the key available in the CSV file?

Reference: How to convert JSON to CSV format and store in a variable

JSON

var data={
  "items": [
    {
      "bandwidth": "",
      "destination_ipv4": "",
      "destination_ipv6": ""
    },
    {
      "interface": "",
      "alarm": false,
      "service": [
        
      ]
    },
    {
      "unit": {
        "name": "operation",
        "shaping-rate": {
          "rate": "1G"
        }
      },
      "ipv6_address": ""
    },
    {
      "vrf": ""
    }
  ]
};

Current result
数据未完全从JSON转换为CSV。

Expected result
数据未完全从JSON转换为CSV。

JS

function download_file(data) {
    const items = data.items
    const replacer = (key, value) => value === null ? '' : value
    const header = Object.keys(items[0])
    let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
    csv.unshift(header.join(','))
    csv = csv.join('\r\n')

    var link = document.createElement("a");    
    link.id="lnkDwnldLnk";
    document.body.appendChild(link);
    blob = new Blob([csv], { type: 'text/csv' }); 
    var csvUrl = window.webkitURL.createObjectURL(blob);
    var filename = 'Result.csv';
    jQuery("#lnkDwnldLnk")
    .attr({
        'download': filename,
        'href': csvUrl
    });
    jQuery('#lnkDwnldLnk')[0].click();
    document.body.removeChild(link);
}

答案1

得分: 2

不要翻译代码部分,以下是翻译好的内容:

"Instead of just using the first element in data.items you will need to get all keys from all elements in the array.

You can do this using Array.prototype.flatMap

You should use this instead of const header = Object.keys(items[0]);"

英文:

Instead of just using the first element in data.items you will need to get all keys from all elements in the array.

You can do this using Array.prototype.flatMap

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const data = {
  &quot;items&quot;: [{
      &quot;bandwidth&quot;: &quot;&quot;,
      &quot;destination_ipv4&quot;: &quot;&quot;,
      &quot;destination_ipv6&quot;: &quot;&quot;
    },
    {
      &quot;interface&quot;: &quot;&quot;,
      &quot;vlan&quot;: null,
      &quot;service&quot;: &quot;&quot;
    },
    {
      &quot;ipv4_address&quot;: &quot;&quot;,
      &quot;ipv6_address&quot;: &quot;&quot;
    },
    {
      &quot;vrf&quot;: &quot;&quot;
    }
  ]
};

const items = data.items;
const header = items.flatMap(item =&gt; Object.keys(item));

console.log(header);

<!-- end snippet -->

You should use this instead of const header = Object.keys(items[0]);

答案2

得分: 2

这是我的版本

var data = { "items": [{ "bandwidth": "A", "destination_ipv4": "B", "destination_ipv6": "C" }, { "interface": "D", "vlan": null, "service": "E" }, { "ipv4_address": "F", "ipv6_address": "G" }, { "vrf": "H" }] };
const items = data.items;
let rows = [];
const header = items.map(item => {
    rows = rows.concat(Object.values(item));
    return Object.keys(item);
})
    .flat()
    .join(",");
const csv = [header, rows.join(",")].join("\n");
console.log(csv)

请注意,我只对代码进行了翻译,没有翻译注释部分。

英文:

Here is my version

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var data = { &quot;items&quot;: [{ &quot;bandwidth&quot;: &quot;A&quot;, &quot;destination_ipv4&quot;: &quot;B&quot;, &quot;destination_ipv6&quot;: &quot;C&quot; }, { &quot;interface&quot;: &quot;D&quot;, &quot;vlan&quot;: null, &quot;service&quot;: &quot;E&quot; }, { &quot;ipv4_address&quot;: &quot;F&quot;, &quot;ipv6_address&quot;: &quot;G&quot; }, { &quot;vrf&quot;: &quot;H&quot; } ] };
const items = data.items;
let rows = [];
const header = items.map(item =&gt; {
    rows = rows.concat(Object.values(item));
    return Object.keys(item);
  })
  .flat()
  .join(&quot;,&quot;)
const csv = [header, rows.join(&quot;,&quot;)].join(&quot;\n&quot;);
console.log(csv)

<!-- end snippet -->

答案3

得分: 0

在提供的JavaScript代码中,header变量用于存储items数组中第一个对象的键。这意味着只有第一个对象的键将被用作CSV文件中的标题。要在CSV文件中包括所有对象的所有键,可以按如下修改代码:

function download_file(data) {
  const items = data.items;
  const replacer = (key, value) => value === null ? '' : value;

  // 从items数组中的所有对象获取所有唯一键
  const allKeys = items.reduce((keys, obj) => {
    Object.keys(obj).forEach(key => {
      if (!keys.includes(key)) keys.push(key);
    });
    return keys;
  }, []);

  const csv = items.map(row => allKeys.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));

  // 添加包含所有键的标题行
  csv.unshift(allKeys.join(','));

  const csvString = csv.join('\r\n');

  var link = document.createElement("a");
  link.id="lnkDwnldLnk";
  document.body.appendChild(link);
  blob = new Blob([csvString], { type: 'text/csv' });
  var csvUrl = window.webkitURL.createObjectURL(blob);
  var filename = 'Result.csv';
  jQuery("#lnkDwnldLnk")
    .attr({
      'download': filename,
      'href': csvUrl
    });
  jQuery('#lnkDwnldLnk')[0].click();
  document.body.removeChild(link);
}

这个修改后的代码使用reduce方法迭代items数组中的每个对象,并收集所有唯一键。然后使用这些键创建CSV文件中的标题行。

通过这个修改,CSV文件将包括items数组中所有对象的所有键。

英文:

In the provided JavaScript code, the header variable is used to store the keys of the first object in the items array. This means that only the keys of the first object will be used as the header in the CSV file. To include all the keys from all the objects in the CSV file, you can modify the code as follows:

function download_file(data) {
  const items = data.items;
  const replacer = (key, value) =&gt; value === null ? &#39;&#39; : value;
  
  // Get all unique keys from all objects in the items array
  const allKeys = items.reduce((keys, obj) =&gt; {
    Object.keys(obj).forEach(key =&gt; {
      if (!keys.includes(key)) keys.push(key);
    });
    return keys;
  }, []);
  
  const csv = items.map(row =&gt; allKeys.map(fieldName =&gt; JSON.stringify(row[fieldName], replacer)).join(&#39;,&#39;));
  
  // Add the header row with all keys
  csv.unshift(allKeys.join(&#39;,&#39;));
  
  const csvString = csv.join(&#39;\r\n&#39;);
  
  var link = document.createElement(&quot;a&quot;);    
  link.id=&quot;lnkDwnldLnk&quot;;
  document.body.appendChild(link);
  blob = new Blob([csvString], { type: &#39;text/csv&#39; }); 
  var csvUrl = window.webkitURL.createObjectURL(blob);
  var filename = &#39;Result.csv&#39;;
  jQuery(&quot;#lnkDwnldLnk&quot;)
    .attr({
      &#39;download&#39;: filename,
      &#39;href&#39;: csvUrl
    });
  jQuery(&#39;#lnkDwnldLnk&#39;)[0].click();
  document.body.removeChild(link);
}

This modified code uses the reduce method to iterate over each object in the items array and collect all the unique keys. It then uses these keys to create the header row in the CSV file.

With this modification, all the keys from all the objects in the items array will be included in the CSV file.

huangapple
  • 本文由 发表于 2023年6月22日 18:40:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531057.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定