2

I'm trying to convert a JSON-object to a CSV file in javascript.

I have used all kinds of libraries and pre-made functions, but nothing seems to work for me as soon as the JSON starts to nest.

This is one of the functions I am using:

function ConvertToCSV(objArray) {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
        var str = '';

        for (var i = 0; i < array.length; i++) {
            var line = '';
            for (var index in array[i]) {
                if (line != '') line += ','

                line += array[i][index];
            }

            str += line + '\r\n';
        }

        return str;
    }

I have seen people say that the complexity of your json object should not be of influence to to your output, but all I am getting is: [object Object],[object Object],[object Object], etc..

Online you can find json to csv converters that actually manage to create a nicely done csv file with extra headers if a property is double nested. So any hints in the right direction of how I would write a function like this would be really appreciated. If you know of any libraries that can do this that would be great too!

(It is probably worth stating that when I use a single-layered json object the csv file won't show [object,Object] and instead gives me a nice csv file, its only when it starts to get nested that it doesnt work anymore)

UPDATE: As requested, this is the kind of JSON file im working with.

[
{
"HEADER": {
    "SEARCH": "Zoeken",
    "FILTER": "Filter",
    "MISC": "Overige"
},
   "FORM": {
    "REQUIRED": "Dit veld is verplicht",
    "MINLENGTH": "De input is te kort",
    "MAXLENGTH": "De input is te lang",
    "EMAIL": "Geen geldig e-mailadres"
},
"TODO": "TODO: Hier moet nog een leuke tekst komen! dit komt uit een vertaling, in dit geval Nederlands. Nu is Nederlands natuurlijk op dit moment de enige taal maar het zou mooi zijn als hier in de toekomst veer vertalingen bij komen..."
}
 ]

I also wanted to add that when I use 'agnes.js' I don't get [Object object] as output, but instead every single letter is added underneath each other and there are no more than 1 column.

9
  • please add an example of your object. Commented Sep 26, 2016 at 9:00
  • I tried your sample code.. I'm not getting [object Object] Commented Sep 26, 2016 at 9:01
  • @NinaScholz added example of my json Commented Sep 26, 2016 at 9:08
  • @BlazeSahlzen was your json also nested? Does it work with my sample json code too? Commented Sep 26, 2016 at 9:24
  • It won't work for nested json obviously. Because the toString method always returns [object Object] for an object. You can stringify it though. Commented Sep 26, 2016 at 9:27

1 Answer 1

1

TRIVIAL SOLUTION

function ConvertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ',';

            // If array[i][index] is an object then we loop over its properties
            // And add it to the CSV string in a similar manner
            if (typeof array[i][index] === 'object') {
                var inner_obj = array[i][index];

                for (var index1 in inner_obj) {
                    if (line != '') line += ','

                    line += '"' + inner_obj[index1] + '"';
                }
            } else {
                line += '"' + array[i][index] + '"';
            }
        }

        str += line + '\r\n';
    }
    return str;
}

EXPLANATION

Since the object structure will remain consistent, what I did was run a if-else check to see if the array[i][index] is an object or not. If it is an object then we simply run a loop over its properties and add it to the CSV string like before.

Also, I placed quotes around all elements so that strings which have , don't get misinterpreted as the CSV's element separator.

Sign up to request clarification or add additional context in comments.

3 Comments

Yay! atleast I'm getting values into the csv file now.. There is just one problem left though. All the titles are gone, its just 1 row now with all the individual titles. Would you know how to add this? Or doesn't my function add these in the first place? I'm starting to think I should just remove the nesting and keeping it simpler.
By titles do you mean the headers? No, your function doesn't handle the headers.
@MaxTaylor you should upvote/accept this answer if it helped you.

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.