Home > Article > Web Front-end > How to Convert JSON to CSV in JavaScript and Store it in a Variable?
Converting JSON to CSV in JavaScript and Storing in Variable
To convert JSON data to CSV format in JavaScript and store it in a variable, follow these steps:
Parse the JSON Data: Use the JSON.parse() method to convert the JSON string into a JavaScript object.
<code class="javascript">var json3 = JSON.parse(json_data);</code>
Convert Nested Objects to Array: If the JSON data contains nested objects, use the map() method to convert them into an array.
<code class="javascript">var items = json3.items.map(function(item) { return item; });</code>
Extract Field Names: Get the list of field names by accessing the keys of the first item in the array.
<code class="javascript">var fields = Object.keys(items[0]);</code>
Create CSV Header: Join the field names with a separator (e.g., ",") to create the CSV header.
<code class="javascript">var header = fields.join(',');</code>
Convert Objects to CSV Rows: Iterate over the items array and convert each item into a CSV row.
<code class="javascript">var rows = items.map(function(item) { return fields.map(function(field) { return item[field] ? '"' + item[field] + '"' : ''; }).join(','); });</code>
Join Header and Rows: Combine the CSV header and rows into a single string.
<code class="javascript">var csv = header + '\n' + rows.join('\n');</code>
Store in Variable: Assign the generated CSV string to a variable.
<code class="javascript">var csv_data = csv;</code>
To handle escape characters like 'u2019', use the String.replace() method with a regular expression to replace them with their corresponding characters.
<code class="javascript">var unescaped_csv = csv_data.replace(/\u2019/g, "'");</code>
This will convert the escape character back to a normal apostrophe character.
The above is the detailed content of How to Convert JSON to CSV in JavaScript and Store it in a Variable?. For more information, please follow other related articles on the PHP Chinese website!