Reformat a JSON file and save as a new file

I have a lengthy list of one-level JSON data similar to the example below: json-old.json

[
{"stock": "abc", "volume": "45434", "price": "31", "date": "10/12/12"},
{"stock": "abc", "volume": "45435", "price": "30", "date": "10/13/12"},
{"stock": "xyz", "volume": "34465", "price": "14", "date": "10/12/12"},
{"stock": "xyz", "volume": "34434", "price": "14", "date": "10/13/12"},
{"stock": "zzz", "volume": "76755", "price": "65", "date": "10/12/12"},
{"stock": "zzz", "volume": "85646", "price": "67", "date": "10/13/12"}
]

I am looking for a way to transform this file into a new format in another file: json-new.json

[
{ 
   "abc": {
      "10/12/12": { "volume": "45434", "price": "31" },
      "10/13/12": { "volume": "45435", "price": "30" }
   }
},
{
   "xyz": {
      "10/12/12": { "volume": "34465", "price": "14" },
      "10/13/12": { "volume": "34434", "price": "14" }
   }
},
{
   "zzz": {
      "10/12/12": { "volume": "76755", "price": "65" },
      "10/13/12": { "volume": "85646", "price": "67" }
   }
}
]

Essentially, I want to restructure and nest the data based on the 'stock' and 'date' properties.

Are there any libraries available in JavaScript or Node.js that can assist with automating this conversion process? I have numerous files in a folder that need to be transformed into a single file with the desired structure (to facilitate uploading to a database like Firebase).

Answer ā„–1

One helpful method to consider is Array.reduce

const data = [
    { "stock": "abc", "volume": "45434", "price": "31", "date": "10/12/12" },
    { "stock": "abc", "volume": "45435", "price": "30", "date": "10/13/12" },
    { "stock": "xyz", "volume": "34465", "price": "14", "date": "10/12/12" },
    { "stock": "xyz", "volume": "34434", "price": "14", "date": "10/13/12" },
    { "stock": "zzz", "volume": "76755", "price": "65", "date": "10/12/12" },
    { "stock": "zzz", "volume": "85646", "price": "67", "date": "10/13/12" }
]

const formattedData = data.reduce((result, current) => {
    const {stock, date, ...rest} = current

    const info = result[stock] || {}
    info[date] = rest
    result[stock] = info

    return result
}, {})

console.log([formattedData])

Answer ā„–2

To implement a for loop, you can follow the example below:

var data = [
        { "name": "apple", "quantity": "100", "price": "$1", "date": "12/01/2021" },
        { "name": "banana", "quantity": "50", "price": "$0.50", "date": "12/02/2021" },
        { "name": "orange", "quantity": "75", "price": "$0.75", "date": "12/01/2021" }
    ];
    var output = [];
    var results = []
    for (var item in data)
    {
        var fruit=data[item];
        var info = {
            'quantity': fruit.quantity,
            'price': fruit.price
        }
        var inventory = output[fruit.name] || {};
        inventory[fruit.date] = info;
        output[fruit.name] = inventory;
    }
    for (i in output) {
        var newObj = {}
        newObj[i] = output[i];
        results.push(newObj)
    }
    console.log(results);
   // console.log(JSON.stringify(results));

You can now use the JSON format as your new data structure.

Answer ā„–3

This piece of code should get the job done:

const fs = require('fs')

const groupBy = (items, key) => items.reduce(
    (result, item) => ({
      ...result,
      [item[key]]: [
        ...(result[item[key]] || []),
        item,
      ],
    }), 
    {},
);

const inputFileName = process.argv[2]
const outputFileName = process.argv[3]

const jsonData = JSON.parse(fs.readFileSync(inputFileName, 'utf8'));
const groupedStock = groupBy(jsonData,'stock')
const groupedDate = {}
for(stock in groupedStock)
    groupedDate[stock] = groupBy(groupedStock[stock],'date')

const filteredData = {}
for(stock in groupedDate){
    filteredData[stock] = {}
    for (date in groupedDate[stock]) {
        filteredData[stock][date] = {
            price: groupedDate[stock][date][0].price,
            volume: groupedDate[stock][date][0].volume
        }
    }
}

const result = []
for(stock in filteredData)
    result.push({
        [stock]: filteredData[stock]
    })


fs.writeFileSync(outputFileName, JSON.stringify(result,null,2));

To run this program, use

node convert.js json-old.json json-new.json

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

Team member invitation feature on a MERN web platform

I've been working on a MERN stack website where every user who signs up will receive their own subdomain based on the username they choose. Progress so far: Users can successfully create accounts and obtain their personalized subdomains upon sign-up ...

Using Sinonjs fakeserver to handle numerous ajax requests

I utilize QUnit in combination with sinon. Is there a way to make sinon's fakeserver respond to multiple chained ajax calls triggered from the same method? module('demo', { beforeEach: function(){ this.server = sinon.fakeServer. ...

Jquery Ajax is met with a 400 error indicating a BAD request

I've encountered an issue while trying to send data to my local DB server. Every time I attempt to send the data, I keep receiving a 400 Bad Request error. var studentEmail = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail ...

Step-by-step guide on utilizing Create React App for installing React:

Hey there, I'm completely new to React and I'm struggling with the installation process. I've downloaded Node.js and have versions v12.18.3 and NPM 6.14.6 installed on my system. However, whenever I try to follow the create-react-app install ...

Is it possible to deinitialize data tables (remove from memory)?

I'm currently utilizing data-tables (with jQuery) on my website. The particular data-table I have implemented seems to be consuming excessive memory in javascript, causing a slowdown in other functionalities. Is there a way for me to de-initialize th ...

Manipulate JSON insertions and character replacements using JavaScript or Python

I have a JSON file that contains an array of 500 objects. The structure of each object is as follows: { "books":[ { "title":"Title 1", "year":"2012", "authors":"Jack ; George", }, { "title":"Title 2", "year":" ...

Issue encountered when trying to remove an event while a dialog is closed in a React useEffect

While working with my open dialog, I attempted to include a 'key-down' event. Unfortunately, the event continues to trigger even after the dialog is closed. To address this issue, I encapsulated the event handling function within the useEffect h ...

Customize input box type based on JSON data using ng-repeat directive in AngularJS

Looking to implement a dynamic form using angular JS. I can successfully use ng-repeat to iterate through JSON fields and display an input box for each. Now I need to customize the input type based on field data from JSON, whether it's 'input&a ...

Unable to retrieve DOM value due to Vue.js template being inaccessible in Chromium, including from both DevTools and extensions

Currently, Iā€™m developing a Chrome extension that needs to retrieve specific values from a webpage such as the item title. However, instead of fetching the actual title, it is reading a Vue.js template variable. Even when I use DevTools to inspect the p ...

Using nodeMCU along with ajax means that instead of refreshing just a single element, the entire web page

I'm in need of assistance with reloading two elements on my webpage. I am working with small electronics and the NodeMCU as its brain. I require two outputs (connected to relays) and two inputs. For the inputs, I would like them to update periodicall ...

Struggling to display Firebase Auth information resulting in 'undefined' value within React web application

When loading a user's profile page, I am trying to display their displayName and email information retrieved from Firebase Auth. I have implemented this logic within the 'componentDidMount' method by updating the state with the response dat ...

How can I utilize the mapv tool created by Baidu in a Node project?

I need assistance converting the following code to a node environment. The code can be found at Here is the code snippet: var map = new BMap.Map(slice.selector, { enableMapClick: false }); // Create Map instance map.centerAndZoom( ...

Is it possible to combine Mongoose Materialized Path with Mongoose Restify?

After successfully implementing a schema/model for a recursive tree structure in Mongoose, I have decided to enhance my current setup by integrating two specific packages designed to streamline the process: Utilizing mongoose-mpath will allow me to man ...

Having trouble fetching data from a connected Android device to a localhost endpoint using React-Native

I am relatively new to React Native and I am currently working on developing an application. I have a JSON post request that functions correctly on Postman and Expo when accessed through a web browser at http://127.0.0.1:8080. However, when attempting to r ...

Enhance an existing JsonObject in javax.json by introducing a fresh JsonNumber

When it comes to adding properties to an existing instance of JsonObject, dealing with boolean values is simple: JsonObject jo = ....; jo.put("booleanProperty", JsonValue.TRUE); However, the process becomes more challenging when trying to add a JsonNumbe ...

The combination of Docker and Node.js .mjs modules is a powerful tool

I am facing a challenge with my express application where all the JS files have the *.mjs extension. To run the server, I use node index.mjs, and it works perfectly. However, now I am attempting to containerize the app. This is the basic Dockerfile I have ...

Guide on showing string array values in an alert popup using JavaScript

I am struggling to display a string array in a JavaScript alert popup. The goal is to show the string index or Serial Number, followed by a space and then a line break before displaying the value of each string in the array. Unfortunately, my current code ...

Leveraging the power of Express and everyauth for implementing conditional authentication with Google OAuth2

Trying to integrate everyauth with Google OAuth2 has been a bit challenging for me. I specifically need authentication to be successful only if the user belongs to my company's Google Apps domain. However, I am struggling to find a way to gracefully s ...

How to send emails in the background using a React Native app

I'm looking to incorporate email functionality into a React Native app so that it can send messages automatically when certain actions occur in the background. ...

What is the best way to deserialize a JavaScript date with Jackson library?

I receive a date string from ExtJS in the format: "2011-04-08T09:00:00" When attempting to deserialize this date, it automatically adjusts the timezone to Indian Standard Time (adding +5:30 to the time). Here is my current method for deserializing the ...