Skip to content

unwindArrays:true with an empty array fails to convert the object. #151

@Bakabake

Description

@Bakabake

Background Information

  • Module Version: 3.7.1
  • Node/Browser Version: 10.16.0

The issue I'm reporting is with:

  • json2csv
  • csv2json

I have...

  • searched to see if an issue has already been reported.
  • verified that my JSON/CSV data is valid (using something like http://jsonlint.com or https://csvlint.io/).
  • tried upgrading to the latest version of json-2-csv (since the issue may already be fixed).

Expected Behavior

When encountering an empty array in an object, and unwindArrays: true, a valid value should be written out.

Actual Behavior

If the JSON object contains an empty array, and 'unwindArrays: true`, the object will not be written to csv.

Data Sample

JSON:

[
    {   
        "Desc": "This will convert" 
    },
    {   
        "Desc": "This will not convert if 'unwindArrays' is true",
        "arr": []
    },
    {   
        "Desc": "This will convert also",
        "arr": ["value1"]
    }
]

Code Example

// Please include a simple example to replicate the issue
let converter = require('json-2-csv');

let options = {
    unwindArrays: true
}

converter.json2csvAsync(json, options)
    .then((csv) => { console.log(csv) })

Output

With unwindArrays: true:
Desc,arr
This one will convert,undefined
This will convert also,value1

With unwindArrays: false:
Desc,arr
This one will convert,undefined
This will not convert if 'unwindArrays' is true,[]
This will convert also,"[""value1""]"

Quick Note

To fix this, in utils.js:unwindItem(), change

function unwindItem(accumulator, item, fieldPath) {
    //...
    if (Array.isArray(valueToUnwind) ) {
    //...
}

to

function unwindItem(accumulator, item, fieldPath) {
    //...
    if (Array.isArray(valueToUnwind) && valueToUnwind.length) {
    //...
}

That seemed to fix the issue in my tests -- it output the value []

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions