简体   繁体   中英

How to export csv from JSON data with using JQ

This is what I tried

curl -s 'https://api.hoge.com/api/?symbol=TEST' \ | jq -r '.[] | select(.bids ) | to_entries| map(.value) | @csv ' > OrderBook.csv;

Then I got this error back

jq: error (at <stdin>:0): Cannot index number with string "bids"

The JSON data that I can retrieve from the url above is this

{"lastUpdateId":18891938,
"bids":[
    ["3.23600000","101.76600000"],
    ["3.23500000","2161.63600000"],
    ["3.23100000","30.95000000"],
    ["3.23000000","3.12600000"],
    ["3.22900000","303.95100000"]
],
"asks":[
    ["3.24100000","15.90200000"],
    ["3.24200000","1679.00000000"],
    ["3.24500000","953.98800000"],
    ["3.24800000","7.57700000"],
    ["3.25400000","37.26700000"]
]}

How can I export it as csv file something like this below

"bids","3.23600000","101.76600000"
"bids","3.23500000","2161.63600000"
"bids","3.23100000","30.95000000"
"bids","3.23000000","3.12600000"
"bids","3.22900000","303.95100000"
"asks","3.24100000","15.90200000"
"asks","3.24200000","1679.00000000"
"asks","3.24500000","953.98800000"
"asks","3.24800000","7.57700000"
"asks","3.25400000","37.26700000"

Pipe into:

jq -r 'keys[] as $k | select(.[$k]|type=="array") |[$k]+.[$k][]|@csv'

Or use keys_unsorted .

This solution is not robust. You might like to consider this alternative:

keys[] as $k |[$k]+.[$k][]? | @csv

See it in action at https://jqplay.org/s/8zMbHxlfoz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM