transforming JSON into CSV structure

I am attempting to utilize a JSON file as input data. Below is an excerpt of sample data.

[
{
id: 1671349531,
name: "A Wild Restaurant Expansion",
blurb: "We are looking to expand from our current location to a new and better facility...",
goal: 17000,
pledged: 0,
state: "live",
slug: "a-wild-restaurant-expansion",
...
}

Is it feasible to convert this intricate JSON format into a CSV for easier data manipulation in R?

For instance, there are key categories within the data like basic information, photo, creator, location, category, urls.

Would it be practical to create a CSV file with subcategories such as basic_information.id, creator.id, etc.?

Answer №1

After doing some research, I have found a solution by using this npm package to convert JSON to CSV format.

To implement this, first install the node package and then utilize the code snippet below with your own JSON data:

var converter = require('json-2-csv');

var documents = [
    {
        Make: 'Nissan',
        Model: 'Murano',
        Year: '2013',
        Specifications: {
            Mileage: '7106',
            Trim: 'S AWD'
        }
    },
    {
        Make: 'BMW',
        Model: 'X5',
        Year: '2014',
        Specifications: {
            Mileage: '3287',
            Trim: 'M'
        }
    }
];

var json2csvCallback = function (err, csv) {
    if (err) throw err;
    console.log(csv);
};

converter.json2csv(documents, json2csvCallback);

The output of this will be as follows:

Make,Model,Year,Specifications.Mileage,Specifications.Trim
Nissan,Murano,2013,7106,S AWD
BMW,X5,2014,3287,M

Answer №2

Here's an alternative approach that doesn't rely on json-2-csv for handling complex data:

// Example of some intricate demo data
var data = [
    {
        "id": "111",
        "name": "Johny Smith",
        "age": "23",
        "dates": [
            {
                "birthday": "01.01.1990",
                "nameday": "02.02",
                "phone": {
                    "home": "02123123123123",
                    "mobile": "07124123123",
                }
            }
        ]
    },
    {
        "id": "222",
        "name": "Jane Alex",
        "age": "43",
        "dates": [
            {
                "birthday": "06.06.1997",
                "nameday": "03.03",
                "phone": {
                    "home": "029999999999999",
                    "mobile": "0788888888",
                }
            }
        ]
    }
];

// Convert the data to a CSV-ready string
var converted = toCsv(data);

// Automatically generate and download the .CSV file
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(converted));
element.setAttribute('download', "Output.csv");
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);


//////////////////////////////////// THE MAGIC ////////////////////////////////////

function toCsv(arr) {
    arr = pivot(arr);
    return arr.map(function (row) {
        return row.map(function (val) {
            return isNaN(val) ? JSON.stringify(val) : +val;
        }).join(',');
    }).join('\n');
}

function toConsumableArray(arr) {
    if (Array.isArray(arr)) {
        for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
            arr2[i] = arr[i];
        }
        return arr2;
    } else {
        return Array.from(arr);
    }
}

function pivot(arr) {
    var mp = new Map();

    function setValue(a, path, val) {
        if (Object(val) !== val) {
            // primitive value
            var pathStr = path.join('.');
            var i = (mp.has(pathStr) ? mp : mp.set(pathStr, mp.size)).get(pathStr);
            a[i] = val;
        } else {
            for (var key in val) {
                setValue(a, key == '0' ? path : path.concat(key), val[key]);
            }
        }
        return a;
    }

    var result = arr.map(function (obj) {
        return setValue([], [], obj);
    });
    let outcome = ([[].concat(toConsumableArray(mp.keys()))].concat(toConsumableArray(result)));

    return outcome;
}

Check out the working example on JS Fiddle -> https://jsfiddle.net/gbktnd1j/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing server-side variables with JavaScript in Node.js, Express.js, and EJS

Hello everyone, I am just getting started with backend programming and I'm currently working on a project where I need to send an array of objects to the client. My goal is for the client to then add an object to this array. I am using node.js in conj ...

Is the behavior of a function with synchronous AJAX (XMLHttpRequest) call in JavaScript (Vanilla, without jQuery) the same as asynchronous?

I'm facing an issue with a file named tst.html and its content: part two (purely for demonstration, no extra markup) The challenge arises when I try to load this file using synchronous AJAX (XMLHttpRequest): function someFunc() { var str = &ap ...

Is there a way to prevent the Alt+F4 function from closing tabs in the Internet Explorer browser

Ctrl+W and Alt+F4 can be used to close the IE browser, but I am looking to disable this default action. While I have found a way to handle the Ctrl+W command, I am struggling with disabling the Alt+F4 event. It seems that other Alt+Key events like Alt+En ...

managing arrays in JavaScript with multiple tables

**I have successfully written code for calculating the sum of inputs in one table** $('#example122').on('input', '.calculate', function () { calculateTotal(); }); function calculateTotal() { var grandTotal = 0; $ ...

Tips for verifying if two passwords match during registration and displaying an error message if they do not match

How can I ensure that the passwords entered in a registration form match and how do I validate the entire form to be correct? <form id="registerForm" method="POST" action="/register" class="form2"> ...

VueJS method for making an HTTP GET request

Attempting to make an http get request using Vue js. I can't seem to find any issues with the logic, although I'm not very experienced with vuejs. Continuously encountering these two errors: [Vue warn]: Error in mounted hook: "TypeError: Cann ...

Setting up Datatables using AngularJS

I am working on a controller that organizes song rankings based on sales data. Upon initialization, the controller automatically sends an HTTP GET request to retrieve all the songs needed for display (currently set at the top 20 songs). If I ever need to a ...

Fundamental JavaScript feature experiencing functionality issues

Greetings, this is my debut in this space and I am encountering some challenges as a beginner in the world of coding. It seems that passing arguments to parameters is where I'm hitting a roadblock, or perhaps there's a simple detail that I'm ...

A recursive function that utilizes a for loop is implemented

I am encountering a critical issue with a recursive function. Here is the code snippet of my recursive function: iterateJson(data, jsonData, returnedSelf) { var obj = { "name": data.groupName, "size": 4350, "type": data.groupType }; if ...

Java: Combine values of the same type into a single JSON object

Let's say I have 3 different dates like this: try { DateDetails GetDateDetailsResp = GET.getDateDetails; Date date1 = GetDateDetailsResp.dateDetails.date1; Date date2 = GetDateDetailsResp.dateDetails.date2; Date date3 = GetDateDetai ...

Creating Eye-Catching Images by Incorporating Image Overlays Using Just One Image

I'm facing a bit of a challenge here. I need to figure out how to overlay an image onto another image using just a single image tag. Specifically, I want to add a resize icon to the bottom right corner of an image to let users know they can resize it ...

jquery-powered scrollable content container

<script language="javascript"> $(document).ready(function($) { var methods = { init: function(options) { this.children(':first').stop(); this.marquee('play'); }, play: function( ...

Verify if an express module has a next() function available

Is there a method to check if there is a function after the current middleware? router.get('/', function(req, res, next){ if(next){//always returns true } }); I have a function that retrieves information and depending on the route, thi ...

You can install the precise version of a package as mentioned in package.json using npm

At this moment, executing the command npm install will download the latest versions of packages. Is there a way to install the exact versions specified in the package.json file? ...

The issue of javascript Map not updating its state is causing a problem

I've encountered an issue where my components are not re-rendering with the updated state when using a map to store state. const storage = (set, get) => ({ items: new Map(), addItem: (key, item) => { set((state) => state.items ...

Determine the specific button that was clicked within a React component

I have a challenge with dynamically generated material UI buttons. I am trying to identify which button was clicked by obtaining the value of the name attribute that I assigned to each button. Is there a way to accomplish this? In essence, I need to retrie ...

transferring data between PHP frames

Having a PHP variable within a frame from a frameset that must be passed to two other frames at the same time is proving to be a challenge. One of those frames refreshes every 5 seconds, making it easy to extract the variable from the URL. The other frame, ...

Executing JavaScript code upon successful form submission: An overview

I need help with my Asp.Net MVC web application. I am trying to implement a feature where some code runs on the successful response of an API method called upon form submission. Here is the current code snippet: @using (Html.BeginForm("APIMethod", "Confi ...

I'm experiencing an issue with fullCalendar where the dayRender function is not functioning as expected

I have been using fullCalendar and I am looking to customize the color of specific days. I have successfully created an overlay that is displayed when a user clicks on a particular day. Everything works as expected with the overlay, but now I am encounte ...

loading the css and javascript files based on the specified prop parameter

In the process of working on a ReactJS file that utilizes the react-ace library, I currently have the following code implemented. import React, { Component } from 'react'; import 'brace/mode/html'; import 'brace/theme/monokai&apos ...