How to use jq @CSV filter to generate a csv file with values from different json levels

I have a JSON file from the Spotify API that lists all the songs on a specific album. The file is organized as follows:

. .name .tracks.items .tracks.items[] .tracks.items[].artists .tracks.items[].artists[].name .tracks.items[].duration_ms .tracks.items[].name 

I'm using jq to create a csv with the following information: song's artist, song's title, and song's duration. I can do this using the following syntax:

jq -r '.tracks.items[] | [.artists[].name, .name, .duration_ms] | @csv' myfile.json 

Output:

"Michael Jackson","Wanna Be Startin' Somethin'",363400 "Michael Jackson","Baby Be Mine",260666 ... 

However, I would like to also add the value under .name (which represents the name of the album the songs are from) to every row of my csv file. Something that would look like this:

"Thriller","Michael Jackson","Wanna Be Startin' Somethin'",363400 "Thriller","Michael Jackson","Baby Be Mine",260666 ... 

Is it possible to do this using the @csv filter? I can do it by hand by hardcoding the name of the album like this

jq -r '.tracks.items[] | ["Thriller", .artists[].name, .name, .duration_ms] | @csv' myfile.json 

But I was hoping there might be a nicer way to do it.

EDIT:

Here's what the file looks like:

{ "name": "Thriller", "tracks": { "items": [ { "artists": [ { "name": "Michael Jackson" } ], "duration_ms": 363400, "name": "Wanna Be Startin' Somethin'" }, { "artists": [ { "name": "Michael Jackson" } ], "duration_ms": 260666, "name": "Baby Be Mine" } ] } } 
2

1 Answer

See the "Variable / Symbolic Binding Operator" section in jq's documentation

jq -r ' .name as $album_name ### <- THIS RIGHT HERE | .tracks.items[] | [$album_name, .artists[].name, .name, .duration_ms] | @csv ' myfile.json 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like