簡體   English   中英

BASH腳本-使用GREP從JSON輸出返回兩個特定值

[英]BASH script - return two specific values from JSON output using GREP

我從Google API調用中收到以下JSON輸出,我在用grep掙扎着只在“ geometry” \\“ location”下存儲“ lat”和“ lng”值,因此得到如下輸出:

緯度,經度

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "",
               "short_name" : "",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Kildegade",
               "short_name" : "Kildegade",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Horsens",
               "short_name" : "Horsens",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Denmark",
               "short_name" : "DK",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "8700",
               "short_name" : "8700",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Kildegade, 8700 Horsens, Denmark",
         "geometry" : {
            "location" : {
               "lat" : 55.863466,
               "lng" : 9.848784
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 55.86481498029149,
                  "lng" : 9.850132980291503
               },
               "southwest" : {
                  "lat" : 55.8621170197085,
                  "lng" : 9.847435019708499
               }
            }
         },
         "place_id" : "ChIJG8X9xAVjTEYRGwL9QuNARJQ",
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}

我認為我需要在API KEY之后進行GREP調用,但是我有點卡住了,因為我得到的輸出沒有任何GREP,但是在應用任何簡單的GREP時卻什么也沒有。

adresse=$(curl -s "https://maps.googleapis.com/maps/api/geocode/json?address=Kildegade+8700+horsens+denmark"&key=GOOGLE API KEY")

在此之前,我曾使用過一些類似的JSON輸出:

| grep -B 1 "route" | awk -F'"' '/short_name/ {print $4}

但這並不適合此輸出,並且在使用GREP方面還不夠強大;)

任何幫助都會非常有幫助,謝謝;)

jq( https://stedolan.github.io/jq/ )是輕量級且靈活的命令行JSON處理器。

假設您要從json示例中提取latlng字段。

然后,您可以使用jq '.results[].geometry.location' < input.json

請注意,在上面的示例中,我正在考慮將您的json存儲在一個名為input.json的文件中,但是您可以在curl之后使用jq ,例如: curl ... | jq ... curl ... | jq ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM