Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map an object to arrays so it can be converted to csv?

Tags:

json

jq

I'm trying to convert an object that looks like this:

{   "123" : "abc",   "231" : "dbh",   "452" : "xyz" } 

To csv that looks like this:

"123","abc" "231","dbh" "452","xyz" 

I would prefer to use the command line tool jq but can't seem to figure out how to do the assignment. I managed to get the keys with jq '. | keys' test.json but couldn't figure out what to do next.

The problem is you can't convert a k:v object like this straight into csv with @csv. It needs to be an array so we need to convert to an array first. If the keys were named, it would be simple but they're dynamic so its not so easy.

like image 769
Louis Avatar asked Nov 24 '13 21:11

Louis


People also ask

How to convert array of objects to CSV in JavaScript?

Create an empty array first to store all data of an object in form of rows. Using Object. keys() method fetch all keys of an object which are going to be first row of CSV table. map() method iterate over all objects and append all values to “csvRow[]” array along with comma(,) separator using join() method.

How do you turn an array into a map?

To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.


1 Answers

Try this filter:

to_entries[] | [.key, .value] 
  • to_entries converts an object to an array of key/value objects. [] breaks up the array to each of the items in the array
  • then for each of the items, covert to an array containing the key and value.

This produces the following output:

[   "123",   "abc" ], [   "231",   "dbh" ], [   "452",   "xyz" ] 

Then you can use the @csv filter to convert the rows to CSV rows.

$ echo '{"123":"abc","231":"dbh","452":"xyz"}' | jq -r 'to_entries[] | [.key, .value] | @csv' "123","abc" "231","dbh" "452","xyz" 
like image 54
Jeff Mercado Avatar answered Oct 09 '22 23:10

Jeff Mercado