How to convert JSON to CSV using Linux / Unix shell

There are several ways to convert JSON to CSV using Linux or Unix shell, here are a few popular options:

  1. Using jq: jq is a command-line JSON processor that can be used to convert JSON to CSV. The basic command to convert a JSON file to CSV using jq is:
jq -r '.' input.json | jq -r -s '.' | jq -r -c '.[]' | jq -r 'map(keys) | add | unique | .[] as $col | map(. as $row | $col | map($row[.]))[]' | jq -r -c '.' > output.csv
  1. Using csvkit: csvkit is a suite of command-line tools for working with CSV files. To convert a JSON file to CSV using csvkit, you can use the following command:
in2csv input.json > output.csv
  1. Using python: You can also use python and its library pandas to convert json to csv. You can use the following command:
python -c 'import pandas as pd, json; pd.read_json("input.json").to_csv("output.csv", index=False)'
  1. Using jansson: Jansson is a C library for encoding, decoding and manipulating JSON data, you can use the command json_unpack to convert json to csv
json_unpack -c ',' input.json > output.csv

Please note that all of these commands requires the installation of the mentioned tools. Also, depending on the structure of your JSON file, the output may not be exactly as you expect. It’s always a good idea to test the command on a small subset of your data before running it on the entire file.

Leave a Comment