Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

json - JQ separate output

i have a json formatted in this way :

{
  "first_name": "Mario",
  "last_name": "Bros",
  "email": "[email protected]",

}
{
  "first_name": "Luigi",
  "last_name": "Bros",
  "email": "[email protected]",

}

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":"[email protected]"}
{"FirstName":"Luigi"}
{"LastName":"Bros"}
{"Email":"[email protected]"}

I want split with space Mario from Luigi.

question from:https://stackoverflow.com/questions/65830936/jq-separate-output

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...