Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQ If then Else

Tags:

jq

How would I do an if then else on the value of a field? Such as my data I am working with looks like:

  {"_key": "USCA3DC_8f4521822c099c3e",
  "partner_attributions": ["This business is a Yelp advertiser."],
  "showcase_photos": [
["Mathnasium of Westwood - Westwood, CA, United States. Nice and       caring instructors", "http://s3-media1.fl.yelpcdn.com/bphoto/KeKAhvy2HHY4KGpvA24VaA/ls.jpg"],
["Mathnasium of Westwood - Westwood, CA, United States. Prize box and estimation jar!", "http://s3-media3.fl.yelpcdn.com/bphoto/lJWHHCAVaUMfeFD7GDKtHw/ls.jpg"],
["Mathnasium of Westwood - Westwood, CA, United States. New table setup!!!!", "http://s3-media2.fl.yelpcdn.com/bphoto/kVYJrYqDRHPOH4F2uTuFVg/ls.jpg"],
["Mathnasium of Westwood - Westwood, CA, United States. Halloween party", "http://s3-media3.fl.yelpcdn.com/bphoto/wKm5KjF0V8MsPTVSuofPEQ/180s.jpg"],
["Mathnasium of Westwood - Westwood, CA, United States", "http://s3-media4.fl.yelpcdn.com/bphoto/r2981msJm0c1ocU09blb1A/180s.jpg"],
["Mathnasium of Westwood - Westwood, CA, United States", "http://s3-media3.fl.yelpcdn.com/bphoto/r2Vgo18YKeUojDvjQMRF_A/180s.jpg"]
  ],
  "review_count": "24",
  "yelp_id": "t7WyXcABE3xj20G-UqXalA",
  "rating_value": "5.0",
  "coordinates": {
"latitude": "34.042568",
"longitude": "-118.431038"
  }
}

This is just a small sample of it, however I am using this expression to parse it:

{_key, last_visited, name, phone, price_range, rating_value, review_count, updated, url, website, yelp_id} + (if (.partner_attributions | length) > 0 then .partner_attributions == "yes" else  .partner_attributions == "no" end) + ([leaf_paths as $path | {"key": $path | map(tostring) | join("_"),"value": getpath($path)}] | from_entries)

What I want to do is have an If then else for the Partner_attributions field that if there is something there make it a yes and if it is null make it No. I have tried a few things with no success, seems simple enough but having trouble trying to figure it out.

Can someone help?

like image 743
Tom Avatar asked Mar 15 '23 06:03

Tom


2 Answers

Better yet perhaps:

.partner_attributions |= (if length > 0 then "yes" else "no" end)

This just updates the one field without modifying anything else.

like image 88
peak Avatar answered Apr 28 '23 23:04

peak


You need to create an actual object to add to the first object. Change the if expression to:

{partner_attributions: (if (.partner_attributions | length) > 0 then "yes" else "no" end)}
like image 45
jwodder Avatar answered Apr 28 '23 23:04

jwodder