node-csv-stringify icon indicating copy to clipboard operation
node-csv-stringify copied to clipboard

csv-stringify complex json array

Open iuabhmalat opened this issue 5 years ago • 0 comments

Hello, I am trying to convert a json object to csv using csv-stringify, but the result is not what I expected. Here's the code that I am working with:

var csv = require("csv-stringify")
data = [
  {
    "address": [
      {
        "city": "Springfield",
        "use": "home",
        "line": [
          "493 N East St"
        ],
        "district": "ST. JOHN",
        "postalCode": "39249",
        "state": "MO"
      }
    ]
  },
  {
    "address": [
      {
        "city": "York",
        "use": "home",
        "line": [
          "272 Barkwood St"
        ],
        "district": "PORTER",
        "postalCode": "29912",
        "state": "IL"
      }
    ]
  },
  {
    "address": [
      {
        "city": "La Jolla",
        "use": "office",
        "line": [
          "7221 Vista Rd"
        ],
        "district": "HAMILTON",
        "postalCode": "53949",
        "state": "TN"
      }
    ]
  }
];
csv(data, {
      header: true,
    }, function (err, csv) {
      if (err) return console.error(err);
      console.log(csv);
    });

I was expecting the following result:

address.city, address.use, address.line, address.district, address.postalCode, address.state
"Springfield", "home", "493 N East St", "ST. JOHN", "39249", "MO"
"York", "home", "272 Barkwood St", "PORTER", "29912", "IL"
"La Jolla", "office", "7221 Vista Rd", "HAMILTON", "53949", "TN"

However, the actual result is one-column wide (address) and the three records are in JSON format:

address
"[{""city"":""Springfield"",""use"":""home"",""line"":[""493 N East St""],""district"":""ST. JOHN"",""postalCode"":""39249"",""state"":""MO""}]"
"[{""city"":""York"",""use"":""home"",""line"":[""272 Barkwood St""],""district"":""PORTER"",""postalCode"":""29912"",""state"":""IL""}]"
"[{""city"":""La Jolla"",""use"":""office"",""line"":[""7221 Vista Rd""],""district"":""HAMILTON"",""postalCode"":""53949"",""state"":""TN""}]"

Does csv-stringify deal with complex json arrays or is the actual result expected behavior?

Abhi Malatpure

iuabhmalat avatar Jul 06 '20 15:07 iuabhmalat