How to use jq to output JSONL (one independent JSON object per line)

前端 未结 3 919
说谎
说谎 2020-12-15 17:33

My request sounds trivial but I could not find a way to do it. I have as input an array of JSON objects:

[
    {
        \"foo\": 1,
        \"bar\": 2
    }         


        
相关标签:
3条回答
  • 2020-12-15 17:46

    Found: it's

    map(tostring) | reduce .[] as $item (""; . + $item + "\n")
    

    You also need to use --raw-output.

    0 讨论(0)
  • 2020-12-15 17:51

    The answer to the original question is to use the filter .[] together with the -c command-line option:

    $ jq -c '.[]'
    
    0 讨论(0)
  • 2020-12-15 17:51

    If the input array is too large to fit into memory, you can use jq's so-called "streaming parser".

    Here is an illustration using a generic approach, that is, it makes no assumptions about the items in the top-level array:

    $ echo '[{"foo":"bar"},99,null,{"foo":"baz"}]' |
      jq -cn --stream 'fromstream( inputs|(.[0] |= .[1:]) | select(. != [[]]) )'
    {"foo":"bar"}
    99
    null
    {"foo":"baz"}
    $ 
    
    0 讨论(0)
提交回复
热议问题