zemirco / json2csv

Convert json to csv with column titles
http://zemirco.github.io/json2csv
MIT License
2.71k stars 365 forks source link

echo "" | json2csv Returns error #292

Closed grepsuzette closed 6 years ago

grepsuzette commented 6 years ago

echo "" | json2csv

Error: Invalid data received from stdin
    at Socket.process.stdin.on (/usr/lib/node_modules/json2csv/bin/json2csv.js:116:16)
    at Socket.emit (events.js:185:15)
    at endReadableNT (_stream_readable.js:1106:12)
    at process._tickCallback (internal/process/next_tick.js:178:19)

Do you think it would be possible for empty input to not return above error? I think it would be more convenient in scripts.

knownasilya commented 6 years ago

Not sure we want to do that, because the input is invalid. If you had "[]" and the fields defined, that's another story, since then we can print the headers from the fields passed in as an argument.

juanjoDiaz commented 6 years ago

Exactly.

"" isn't even valid JSON according to the spec.

In any case, unless you pass the headers explicitly, you need to pass either an object with fields or an array where the first element is an object with fields. Otherwise, it's impossible to print anything.

So one option is to pass the headers explicitely using the headers options. Other option, since your use case seems to be scripting so I'd advise that you simply check before calling json2csv.

YOUR_JSON="" # Or whatever logic you have to get the JSON
if [[ !  -z  $param  ]]; then
  echo "Invalid JSON. Exiting"
  exit 1;
fi
echo $YOUR_JSON || json2csv

I'll close this for now. Please feel free to reopen if you think that we are missing anything.

grepsuzette commented 6 years ago

I’ fine with whatever decision but note echo “” won’t actually feed ‘“”’ but an empty string. The csv for it could also be an empty output.

Although I do admit an API should not return an empty result normally.

juanjoDiaz commented 6 years ago

Correct.

The problem is that json2csv input must be a valid JSON object or array and an empty string is not valid JSON at all :)