David Sadler
David Sadler

Reputation: 3

Fish Shell | Command Substitution using curl and JSON for variable assignment

I cannot find any doc for Fish Shell regarding using Command Substitution more than once.

I'm trying to assign the state, city from the JSON result set (jq parser) piped from a curl API query of LocationIQ. 2 Command Substitution 1:(curl) and 2:(jq). I don't need the location variable assignment if I can get the address variable assignment

Purpose of Function: #Take 2 arguments (Latitude, Longitude) and return 2 variables $State, $City

The JSON:

{
  "address": {
    "city": "Aurora",
    "country": "United States of America",
    "country_code": "us",
    "county": "Kane County",
    "postcode": "60504",
    "road": "Ridge Road",
    "state": "Illinois"
  },
  "boundingbox": [
    "41.729347",
    "41.730247",
    "-88.264466",
    "-88.261979"
  ],
  "display_name": "Ridge Road, Aurora, Kane County, Illinois, 60504, USA",
  "importance": 0.2,
  "lat": "41.729476",
  "licence": "https://locationiq.com/attribution",
  "lon": "-88.263423",
  "place_id": "333878957973"
}

My Function:

function getLocation            
   set key 'hidden'
   set exifLat $argv[1]
   set exifLon $argv[2]
   set location (curl -s "https://us1.locationiq.com/v1/reverse.phpkey=$key&lat=$exifLat&lon=$exifLon&format=json" | set address (jq --raw-output  '.address.state,.address.city') )
   
   echo "Location: $location
   echo "state:    $address[1]"
   echo "city:     $address[2]"
end

Error: fish Command substitution not allowed

Works fine using only the curl Command substitution ->removing the: set address & parens for jq.

set location (curl -s "https://us1.locationiq.com/v1/reverse.phpkey=$key&lat=$exifLat&lon=$exifLon&format=json" | jq --raw-output  '.address.state,.address.city')

I'm still pretty novice - maybe there is a better way to achieve my desired result: Assign the JSON State to a variable and City to a variable?

I originally tried (slicing the location[17] - City, location[19] - State) and getting inconsistent results as the fields seem to be dynamic and affecting how many results which affects the ordering.

Any help appreciated!

Upvotes: 0

Views: 2222

Answers (1)

glenn jackman
glenn jackman

Reputation: 247062

I find the nested set confusing. Did you intend to do use $location to hold the downloaded JSON data, and $address to hold the results of jq? If yes, split them out into separate statements

set url "https://us1.locationiq.com/v1/reverse.phpkey=$key&lat=$exifLat&lon=$exifLon&format=json"
set location (curl -s $url)
set address (echo $location | jq --raw-output  '.address.state,.address.city')

Upvotes: 3

Related Questions