Ad

Change JSON Content Field Type Using Node.js

- 1 answer

I have crawled some contents from websites using a third party crawling tool and i got a .json file successfully after the crawl. My jsoncontent looks as shown below:

  {
   "name": "Mi Band 3 (Black)",
   "price": "₹ 1,899.00",
   "rating_count": "22,438",
   "MRP": "₹ 2,199.00",
   "saved_amount": "₹ 300.00 (14%)"
  }

There are plenty of such products crawled, you can see the price, MRP and rating_count are of String type here, I want to change it and make number type, also i want to iterate through the price,rating_count, & MRP fields to remove the unwanted characters. I think i can do it using Node.js, but i am a newbie in scripting language including Node.js, i have read the contents from .json file using the below code after checked few Node.js basics, and worked it

var fs = require('fs');

 fs.readFile('run_results.json','utf8', function (err, data) {
     if (err) throw err;
     console.log('Data here =>', data);
 });

But i can't find any particular solution for my case when i have searched, Kindly give some hints to achieve my task, Thank you.

Ad

Answer

You can pass a transformation function as an argument to JSON.parse to convert numeric strings to Numbers:

var fs = require('fs');

var numericKeys = ["price", "rating_count", "MRP"];

fs.readFile('run_results.json','utf8', function (err, data) {
  if (err) throw err;
  var results = JSON.parse(data, function(key, value) {
    return (numericKeys.indexOf(key) !== -1)
      ? parseFloat(value.replace(/[^0-9.]/g, ''))
      : value;
  });

  console.log(results);
});
Ad
source: stackoverflow.com
Ad