Home >Web Front-end >JS Tutorial >How to Convert JSON to CSV Format in JavaScript?

How to Convert JSON to CSV Format in JavaScript?

DDD
DDDOriginal
2024-11-04 01:15:03808browse

How to Convert JSON to CSV Format in JavaScript?

Converting JSON to CSV Format

The task of parsing JSON data directly in the browser poses challenges due to its encoded form. To convert this data into a more structured format, CSV (Comma-Separated Values), you can employ the following steps:

  1. Parse the JSON data: Convert the JSON string into a JavaScript object using JSON.parse(json).
  2. Create the CSV header: Extract the keys from the first object in the array to form the header row.
  3. Iterate through the data: Use a loop to go through each object in the array.
  4. Extract values: For each object, extract the values using the header keys as references.
  5. Convert to CSV: Join the extracted values with commas to create the CSV row.
  6. Combine rows: Concatenate all the CSV rows to form the final CSV format.

Handling Escaped Characters

To handle escaped characters such as 'u2019', you can use the unescape function from the 'he' module. This module is available as a JavaScript library or online tool that can be used to decode HTML entities.

Complete JavaScript Code

<code class="javascript">// Parse the JSON data
var items = json3.items;

// Create the CSV header
var header = Object.keys(items[0]);

// Construct CSV rows
var csvRows = items.map(function (item) {
  // Extract values
  var values = header.map(function (key) {
    // Handle escaped characters
    return unescaped(item[key]);
  });

  // Convert to CSV row
  return values.join(",");
}).join("\n");

// Add the header to the CSV rows
var csv = header.join(",") + "\n" + csvRows;

console.log(csv);</code>

By following these steps, you can effectively convert the JSON data into CSV format and store it in a variable, enabling you to manipulate and use the structured data as needed.

The above is the detailed content of How to Convert JSON to CSV Format in JavaScript?. 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