-1

I am trying to load sample csv files into project read the content and display according to the filed. I done uploading and file writing but could not optimize the json structure properly for future use case

Here is my sample code :

let csvToJson = require('convert-csv-to-json');
let json = csvToJson.getJsonFromCsv(filepath);
var lines = [];
for(let i=0; i<json.length;i++){
console.log(json[i]);
lines.push(json[i])
}
console.log(lines);
var result3=JSON.stringify(lines);
result3 = result3.replace(/\r?\n|\r/g, " ");
console.log(result3);

My output:

console.log(json[i]) =

Object {name,age,address: "asd,20,"12/76, 11th cross"
"}
browser.js:5358 Object {name,age,address: "dff,30,"33, 11th cross"
"}
browser.js:5358 Object {name,age,address: "f,22,"7g/22, 12th cross"
"}
browser.js:5358 Object {name,age,address: "ghth,55,"4h, 13th cross"
"}

console.log(lines) = [Object, Object, Object, Object, Object]

console.log(result3)

[{"name,age,address":"asd,20,\"12/76, 11th cross\"\r"},
{"name,age,address":"dff,30,\"33, 11th cross\"\r"},
{"name,age,address":"f,22,\"7g/22, 12th cross\"\r"},
{"name,age,address":"ghth,55,\"4h, 13th cross\"\r"},
{"name,age,address":"fhg,44,\"6t, 10th cross\"\r"}]

My expected output:

{name:[],age:[],address:[]}

i.e I want all "name" values should store in the name key similar to "age" and "address". Can anybody help me how to do this?

Vikas Yadav
  • 3,094
  • 2
  • 20
  • 21
batMan007
  • 551
  • 1
  • 10
  • 24
  • Could you add the content of your CSV file to this question? It seems that the convert-csv-to-json library is barely doing anything useful at all here and it would probably be better to get that working than to try to fixup the result afterward. – JLRishe Nov 14 '17 at 07:03

3 Answers3

1

As evident from console.log(json[i]) output, the module convert-csv-to-json is converting your csv file as an array of a single key value pair which means name, age, address are joined into one unit, same goes for their value. At this point of time your file has less key and you can manually map this key.

For the problem above, you can use array#reduce and split() values on comma.

const data = [{"name,age,address": "asd,20,\"12/76, 11th cross\""},{"name,age,address": "dff,30,\"33, 11th cross\""},{"name,age,address": "f,22,\"7g/22, 12th cross\""},{"name,age,address": "ghth,55,\"4h, 13th cross\""}];
var result = data.reduce((res, obj) => {
  let [name, age, ...address] = obj["name,age,address"].split(',');
  res.name.push(name);
  res.age.push(age);
  res.address.push(address.join(''));
  return res;
},{name:[],age:[],address:[]});
console.log(result);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
  • thanx code works but can u tell how to make dynamically without giving direct values like obj["name,age,address"] coz we dono what csv file will upload from user thats why asking – batMan007 Nov 14 '17 at 06:45
  • Please check out [this answer](https://stackoverflow.com/questions/16831250/how-to-convert-csv-to-json-in-node-js), once you have `{name:'boo',age:20, address:'bar'}`, then logic could be made more dynamic. – Hassan Imam Nov 14 '17 at 06:48
0

This should work

let csvToJson = require('convert-csv-to-json');
let json = csvToJson.getJsonFromCsv(filepath);
let obj = JSON.parse(json);
let finalresult = obj.reduce((result, item) => {
    Object.entries(item).forEach(([key, value]) => {
       result[key] = result[key] || [];
       result[key].push(value);
    });
    return result;
}, {});
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • am getting this error : VM199:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 – batMan007 Nov 14 '17 at 05:56
  • What browser are you using? – Jaromanda X Nov 14 '17 at 05:57
  • so, `csvToJson.getJsonFromCsv(filepath);` isn't returning JSON? ... what happens if you change `let obj = JSON.parse(json);` to `let obj = json;` (easiest change for now) – Jaromanda X Nov 14 '17 at 05:58
  • "Yes" check my question " console.log(json[i]) =" this line from this output i have to modify the structure iam looking for – batMan007 Nov 14 '17 at 06:00
  • I don't care about your code for now ... I can't read most of it – Jaromanda X Nov 14 '17 at 06:01
  • check my console.log(json[i]) output : from this i want to make a structure like {name:["a","b","c"],age:[11,12,22],address:["adad","ddd","23,ee"] like this – batMan007 Nov 14 '17 at 06:04
  • ok, what is **your** var called json? is it *JSON* or is it a javascript object? if the other answer is good for you, then mine should work without hardcoding property names - the only issue is, your variable called *json* ... suggests it's JSON, if it is, you need to JSON.parse it before using it, if it isn't JSON, but a javascript Object, then `let obj = json` change in the code should be enough – Jaromanda X Nov 14 '17 at 07:15
0

DEMO

var jsonObj = [{"name,age,address":"asd,20,\"12/76, 11th cross\"\r"},
{"name,age,address":"dff,30,\"33, 11th cross\"\r"},
{"name,age,address":"f,22,\"7g/22, 12th cross\"\r"},
{"name,age,address":"ghth,55,\"4h, 13th cross\"\r"},
{"name,age,address":"fhg,44,\"6t, 10th cross\"\r"}];

var newArray = {
            name:[],
            age:[],
            address:[]
          };
          
for (var i in jsonObj) {
  let [name, age, ...address] = jsonObj[i]["name,age,address"].split(',');
  newArray.name.push(name);
  newArray.age.push(age);
  newArray.address.push(address.join(''));
};

console.log(newArray);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123