Home  >  Article  >  Web Front-end  >  How to Convert JSON to CSV in JavaScript and Store it in a Variable?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 21:10:02634browse

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>
  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>
  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>
  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>
  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>
  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>
  7. 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!

Statement:
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