首页 > 解决方案 > How to extract json data and output to csv using jq

问题描述

My json array file is one long file and has many objects [{},{},{},{}], within each object I need the value for three keys: "STK_NUM":"1004251 ", "DLR_COST":40.32 , "RTL_AMT":9.99. How would I write the jq program to get the key names as headers in my csv file: STK_NUM, DLR_COST,RTL_AMT and the values of these keys from all objects: 1004251,40.32,9.99 ? These three keys are in every object.

Desired csv:

STK_NUM,DLR_COST,RTL_AMT
1004251,40.32,9.99
1012658,29.99,4.69
1232556,18.89,2.49

I've tried:

jq -r .[].STK_NUM HSEitm.json

result:

"1004251"
"1012658"
"1232556"

All my other jq script attempts result in errors because I don't know what I'm doing.

If anyone could show me I would be very grateful.

标签: jsonjqexport-to-csv

解决方案


本着 DRY 的精神:

jq -r '
  ["STK_NUM", "DLR_COST", "RTL_AMT"] as $headers
  | $headers, 
    # Rows:
    map(.[$headers[]]) 
  | @csv
'

推荐阅读