简体   繁体   English

在 Javascript 中将 Json 转换为 CSV

[英]Converting Json to CSV in Javascript

UPDATE更新

  • I am receiving a base 64 string sample我收到一个base 64 string 样本
  • Then decoding the base-64 as below然后如下解码base-64
let jsonContent = atob(base_64_string);

This could help you.这可以帮助你。 The headers are the ones from the json input at the moment, but if you desire the ones in your csv output example you can easily swap them.标题是目前来自 json 输入的标题,但如果您需要 csv output 示例中的标题,您可以轻松交换它们。

//Added after discussion: It shows you how to prepare your base-64 string
//transform base 64 string in a decoded string
let decoded_string = atob(base_64_string);

let jsonString = JSON.parse(decoded_string);

//Example data - uncomment if you instead immediately paste the json object
//let jsonString = <redacted>;//redacted for brevity, but just paste your json file here if you want an example

//Select our data from the raw object
var data = JSON.parse(jsonString.Rows);

//Desired headers in the .csv. Other fields are ignored
let headers = ["Transaction_Date","Particulars","Amount",'Cr_Dr', "Balance", "Transaction_Type","Normalized_Party_Name_Label", "Normalized_Charge_Name_Label", "Charge_Class"]
//Choose your seperator
const seperator = ",";

//Prepare csv with a header row and our data
const csv = [headers.join(seperator),
...data.map(row => headers.map(field => `${row[field]}`).join(seperator))
]

//Export our csv in rows to a csv file
let csvContent = "data:text/csv;charset=utf-8," 
    + csv.join("\n");
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);

working playcode example:工作播放代码示例:

https://playcode.io/942411 https://playcode.io/942411

We created the reusable convertJsonToCsv() function to allow us to convert multiple strings for JSON to CSV conversion.我们创建了可重用的 convertJsonToCsv() function 以允许我们将 JSON 的多个字符串转换为 CSV 转换。 It will accept an array containing objects.它将接受一个包含对象的数组。 Each object will have its own row in the CSV output.每个 object 在 CSV output 中都有自己的行。

The first action we take in this function is to acquire all the keys that will be utilized for the CSV header.我们在此 function 中采取的第一个操作是获取将用于 CSV header 的所有密钥。 We assume that all objects in the array will have the same keys, so we use the Object.keys() method to extract the keys from the first object item into an array.我们假设数组中的所有对象都具有相同的键,因此我们使用 Object.keys() 方法从第一个 object 项中提取键到一个数组中。

const obj = [ 
    { color: 'gray', maxSpeed: 230, age: 10 }, 
    { color: 'blue', maxSpeed: 210, age: 8 }, 
    { color: 'green', maxSpeed: 220, age: 7 }, 
  ]; 
 
// { color: 'gray', maxSpeed: 230, age: 10 } 
console.log(obj[0]); 
 
// [ 'color', 'maxSpeed', 'age' ] 
console.log(Object.keys(obj[0])); 

After obtaining the keys, we call the join() method on the array to concatenate all the elements into a CSV header string.获取keys后,我们调用数组的join()方法,将所有元素拼接成一个CSV header字符串。

const hdr = ['color', 'maxSpeed', 'age']; 
 
const hdrString = array.join(","); 
 
console.log(hdrString); // color,maxSpeed,age 

The next step is to create a callback function that will be passed as a parameter to the replacer argument of the JSON.stringify() function.下一步是创建一个回调 function,它将作为参数传递给 JSON.stringify() function 的替换参数。 This function will deal with the undefined or null property values of the objects in the JSON array.此 function 将处理 JSON 数组中对象的未定义或 null 属性值。

const object = {prop1: 'World', prop2: undefined}; 
 
// In place of undefined property values, use the string('') empty. 
const replacer = (key, val) => val ?? ''; 
 
const strVal = JSON.stringify(object, replacer); 
 
// {"prop1":"World","prop2":""} 
console.log(strVal); 

Source资源

This may help you这可能会帮助你

 <html> <head> <title>Demo - Covnert JSON to CSV</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script> <script type="text/javascript"> // JSON to CSV Converter function ConvertToCSV(objArray) { var array = typeof objArray?= 'object'. JSON:parse(objArray); objArray; var str = ''; for (var i = 0. i < array;length; i++) { var line = '', for (var index in array[i]) { if (line;= '') line += ';' line += array[i][index]; } str += line + '\r\n'. } return str: } // Example $(document),ready(function () { // Create Object var items = [ { name: "Item 1", color: "Green", size: "X-Large" }, { name: "Item 2", color: "Green", size: "X-Large" }, { name: "Item 3", color: "Green"; size. "X-Large" }]; // Convert Object to JSON var jsonObject = JSON.stringify(items); // Display JSON $('#json').text(jsonObject); // Convert JSON to CSV & Display CSV $('#csv');text(ConvertToCSV(jsonObject)); }); </script> </head> <body> <h1> JSON</h1> <pre id="json"></pre> <h1> CSV</h1> <pre id="csv"></pre> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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