2

Hello I am trying to convert some json to cvs, but i have no luck parsing it, i have found some solution for simple json that looks like this

json =  [
    {
      name: "Anil Singh",
      age: 33,
      average: 98,
      approved: true,
      description: "I am active blogger and Author."
    },
    {
      name: 'Reena Singh',
      age: 28,
      average: 99,
      approved: true,
      description: "I am active HR."
    },
    {
      name: 'Aradhya',
      age: 4,
      average: 99,
      approved: true,
      description: "I am engle."
    },
  ];

And i have method like this

convertToCSV(objArray, headerList): string {
    const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
    let str = '';
    let row = 'S.No,';
    // tslint:disable-next-line: forin
    for (const index in headerList) {
      row += headerList[index] + ',';
    }
    row = row.slice(0, -1);
    str += row + '\r\n';
    for (let i = 0; i < array.length; i++) {
      let line = (i + 1) + '';
      // tslint:disable-next-line: forin
      for (const index in headerList) {
        const head = headerList[index];
        line += ',' + array[i][head];
      }
      str += line + '\r\n';
    }
    return str;
  }

And call it like this

const csvData = this.convertToCSV(json, ['name', 'age', 'average', 'approved', 'description']);

The problem i have with one complex object that looks like this

json = [{
        "customer": {
            "emailAddress": "[email protected]"
        },
        "recommendationProductDetails": [{
            "productId": "4288",
            "title": "Title 1",
            "imageWebAddress": "http://url.com/GetImage/2956",
            "webAddress": "http://url.com/",
            "description": "Description 23"
        }, {
            "productId": "8888",
            "title": "Title 8",
            "imageWebAddress": "http://url.com/GetImage/2333",
            "webAddress": "http://url.com/",
            "description": "Description 55"
        }]
    },
    {
        "customer": {
            "emailAddress": "[email protected]"
        },
        "recommendationProductDetails": [{
            "productId": "3333",
            "title": "Title 33",
            "imageWebAddress": "http://url.com/GetImage/333",
            "webAddress": "http://url.com/",
            "description": "Description 333"
        }, {
            "productId": "1111",
            "title": "Title 111",
            "imageWebAddress": "http://url.com/GetImage/111",
            "webAddress": "http://url.com/",
            "description": "Description 111"
        }]
    }
];

Can somebody help for formating this json in cvs, thanks

5
  • are all objects in your json array relevant? use json.filter( obj => obj.name) to get all that have names. use json.filter( obj => obj.name ).map( obj => obj.name + "," + obj.age) to get csv on filtered object with name, age. If i was you i would paste data into chrome console and then play around with code there - its quicker to find solution Commented Apr 3, 2020 at 12:37
  • Can you please make some answer, thanks Commented Apr 3, 2020 at 12:46
  • We'll need an example of your desired output. A complex, nested, JSON object can't be simply represented in a flat CSV format. What do you want your CSV to look like? Commented Apr 3, 2020 at 13:06
  • if i do: [].concat.apply([], json.map(j => j.recommendationProductDetails.map(c => j.customer.emailAddress + "," + c.productId + "," + c.title + "\n"))) to you data above - i get an array of CSV - but im not sure what you want - hope it helps Commented Apr 3, 2020 at 13:31
  • also - you need to handle special chars in your description fields - for commas I would put quotes around these fields , in your csv output - but you may also need to check for quotes, and commas etc. in your description field in your data and decide how to handle these Commented Apr 3, 2020 at 13:32

1 Answer 1

1

There slight workaround to convert such complex object into CSV

Hope below code will be helpful

var jsondata = [{
        "customer": {
            "emailAddress": "[email protected]"
        },
        "recommendationProductDetails": [{
            "productId": "4288",
            "title": "Title 1",
            "imageWebAddress": "http://url.com/GetImage/2956",
            "webAddress": "http://url.com/",
            "description": "Description 23"
        }, {
            "productId": "8888",
            "title": "Title 8",
            "imageWebAddress": "http://url.com/GetImage/2333",
            "webAddress": "http://url.com/",
            "description": "Description 55"
        }]
    },
    {
        "customer": {
            "emailAddress": "[email protected]"
        },
        "recommendationProductDetails": [{
            "productId": "3333",
            "title": "Title 33",
            "imageWebAddress": "http://url.com/GetImage/333",
            "webAddress": "http://url.com/",
            "description": "Description 333"
        }, {
            "productId": "1111",
            "title": "Title 111",
            "imageWebAddress": "http://url.com/GetImage/111",
            "webAddress": "http://url.com/",
            "description": "Description 111"
        }]
    }
];



function flattenObjectKeys(ob) {
    var toReturn = {};

    for (var i in ob) {
        if (!ob.hasOwnProperty(i)) continue;

        if ((typeof ob[i]) == 'object' && ob[i] !== null) {
            var flatObject = flattenObjectKeys(ob[i]);
            for (var x in flatObject) {
                if (!flatObject.hasOwnProperty(x)) continue;

                toReturn[i + '.' + x] = flatObject[x];
            }
        } else {
            toReturn[i] = ob[i];
        }
    }
    return toReturn;
}

function transformToCSV(jsondata, keysArr=[])
{
    var csvData = "";
    var itemList = [];
    jsondata.forEach(customer=>{
        itemList.push(flattenObjectKeys(customer));
    })
    var newKeysNames = Object.keys(itemList[0]);
    var keysMap = {};
    newKeysNames.forEach(newKeyName => {
        keysArr.forEach((oldKeyName)=>{
            let findName = "."+ oldKeyName;
            if( String(newKeyName).indexOf(findName) >= 0)
            {

                keysMap[oldKeyName] = newKeyName;
            }
        })
    });
   // console.log("Keys Map === ", keysMap);
    itemList.forEach((item)=>{
        keysArr.forEach(keyName=>{
            csvData+=item[keysMap[keyName]] +",";
        })
        csvData+='\r\n';
    })


    return csvData;

}

console.log("====================");
console.log(transformToCSV(jsondata, ['title','webAddress','description']));
console.log("====================");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.