skip to Main Content

I have a file containing a sequence of json objects. Using the jq tool, how can I get the first json object from that file?

I have tried jq limit(1; .) input.jsonl but that limits the length of each individual object in the file, rather than giving me just the first object. I have also read through the whole of the jq man page! Maybe I missed something.

3

Answers


  1. Chosen as BEST ANSWER

    Well okay one way to do it is like this:

    jq -c . INPUT.JSONL  | head -n 1 | jq
    

    The -c option says to output the entries one per line, then head gets the first line, then we pretty-print it again with jq. Surely there is a way to do this with just a single invokation of jq?


  2. For an input file like

    {
      "a": "b"
    }
    {
      "c": "d"
    }
    

    you could

    • slurp the entire input and then print the first array element:

      $ jq -s '.[0]' in.json 
      {
        "a": "b"
      }
      
    • use null-input, and then inputs:

      $ jq -n '[inputs][0]' in.json 
      {
        "a": "b"
      }
      
    Login or Signup to reply.
  3. Null input (-n) is useful in such a case:

    jq -n 'input' file.json
    

    The input filter will read a single JSON element from the provided input stream.

    Example:

    jq -n 'input' <<JSON
    { "first element": [ 1, 2 ] }
    { "second element": [ 3, 4, 5 ] }
    JSON
    

    Output:

    {
      "first element": [
        1,
        2
      ]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search