Search code examples
jsonformatjqjsonlines

JQ separate output


i have a json formatted in this way :

{
  "first_name": "Mario",
  "last_name": "Bros",
  "email": "mario.bros@mario.com",

}
{
  "first_name": "Luigi",
  "last_name": "Bros",
  "email": "luigi.bros@mario.com",

}

I have this output with

jq --compact-output 'select(.contact_type | contains("tecnico")) | {FirstName: .first_name},{LastName: .last_name},{Email: .email}'

{"FirstName":"Mario"}
{"LastName":"Bros"}
{"Email":"mario.bros@mario.com"}
{"FirstName":"Luigi"}
{"LastName":"Bros"}
{"Email":"luigi.bros@mario.com"}

I want split with space Mario from Luigi.


Solution

  • Assuming the input is fixed and that each object has a "technico" field, you can run the following:

    jq -r -c '
      select(.contact_type | contains("tecnico"))
      | {FirstName: .first_name},{LastName: .last_name},{Email: .email}, ""
    '
    

    The -r option suppresses the quotation marks around the top-level string, and the trailing , "" has the effect of adding a new-line after each object.

    If you only want the additional blank lines between the objects, then you might find it easier to use a complementary tool such as sed or awk. However, here is a jq-only solution that assumes jq has been called with the -n option in addition to -r -c:

    def nl(stream):
      foreach stream as $s (-1; .+1; if . > 0 then "" else empty end, $s);
    
    nl(inputs | select(.contact_type | contains("tecnico"))
    | if type == "string"
      then . 
      else {FirstName: .first_name},{LastName: .last_name},{Email: .email} 
      end