- 1 year ago
"Cannot iterate over string" error on converting .json to csv using jq
Comment
1 / 1
The "Cannot iterate over string" error in jq occurs when you try to iterate over a string as if it were an array or object. This error typically happens when you attempt to apply an operation that expects an array or object to a string value.
To convert a JSON file to CSV using jq, you need to make sure that the input JSON is an array or an object containing multiple records. Here's an example of how you can convert a JSON array to CSV using jq:
bashjq -r '(.[0] | keys_unsorted) as $keys | $keys, map([.[ $keys[] ]])[] | @csv' input.json > output.csv
Let's break down this command:
(.[0] | keys_unsorted) as $keys
retrieves the keys from the first object in the JSON array and assigns them to the$keys
variable.$keys
outputs the keys as the first row of the CSV.map([.[ $keys[] ]])[]
maps each object in the array to an array of values in the same order as the keys.@csv
converts the array of values to a CSV row.- Finally,
> output.csv
redirects the CSV output to a file namedoutput.csv
.
Make sure that your input JSON is in the correct format (an array or an object with multiple records), and the above command should work without triggering the "Cannot iterate over string" error.