1

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.

2 Answers 2

1

In the spirit of DRY:

jq -r '
  ["STK_NUM", "DLR_COST", "RTL_AMT"] as $headers
  | $headers, 
    # Rows:
    map(.[$headers[]]) 
  | @csv
'
Sign up to request clarification or add additional context in comments.

Comments

0

Try

jq -r '
  
  # Headers
  ["STK_NUM", "DLR_COST", "RTL_AMT"],
  
  # Rows
  (.[] | [.STK_NUM, .DLR_COST, .RTL_AMT])
  
  # Output Format
  | @csv
  
' HSEitm.json

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.