1

I want to parse json loaded from file const notCleanData = JSON.parse(fs.readFileSync('db.json')); to be able to export to CSV using json2csv. I loaded the file and learn how to export, but I can't figure out how to clean JSON from unnecessary part of JSON, cos it's making CSV to be exported in a wrong way. Instead having data from array in separate columns, I get all data under one column with "group" as header. How to convert A.json to B.json for exporting clean JSON to CSV?

A.json

{
   "group" : [
       {
           "A" : "1",
           "B" : "2"
       },
       {
           "A" : "3",
           "B" : "4"
       }        
   ],
   "profile" : {
       "C" : "5"
   }
}

B.json

{
   "A" : "1",
   "B" : "2"
},
{
   "A" : "3",
   "B" : "4"
}       

In short: How to extract data only from "group" and add it to variable?

Win Fan
  • 77
  • 11
  • unnecessary garbage ! i see objects that contain elements, it's organised, if you want to remove an object, use delete json[object]; but there is not a method like cleanJsonGarbage(); – larachiwnl Apr 26 '20 at 18:29
  • Sorry for wording... I will correct the question. – Win Fan Apr 26 '20 at 18:34

1 Answers1

1

You can use jpath for that:

let A = {
   "group" : [
       {
           "A" : "1",
           "B" : "2"
       },
       {
           "A" : "3",
           "B" : "4"
       }        
   ],
   "profile" : {
       "C" : "5"
   }
}
let jp = require('jsonpath');
let B = jp.query(A, '$.group');
console.log(B)

Output:

[ [ { A: '1', B: '2' }, { A: '3', B: '4' } ] ]
Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45
  • Great tip!!! But CSV is still formated wrong. I think square brackets is messing things. I will try `var obj = JSON.parse(jsonAstring);` and then extract with `var group = obj.group;` and than try to export to CSV. I post if it's working. – Win Fan Apr 26 '20 at 19:53
  • @AppleFan Yes, as to csv conversion, the outside square brackets are the problem. Just remove them first - personally, I would go json-to string-remove-back to json-to csv. – Jack Fleeting Apr 26 '20 at 20:18