Home > Web Front-end > JS Tutorial > body text

How to Convert JSON to CSV in JavaScript and Store it in a Variable?

Barbara Streisand
Release: 2024-11-12 21:10:02
Original
604 people have browsed it

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:

  1. 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>
    Copy after login
  2. 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>
    Copy after login
  3. 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>
    Copy after login
  4. 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>
    Copy after login
  5. 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>
    Copy after login
  6. 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>
    Copy after login
  7. Store in Variable: Assign the generated CSV string to a variable.

    <code class="javascript">var csv_data = csv;</code>
    Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template