2013-08-27 100 views
-3

我已經捕捉到了一個猛砸變量下面的命令輸出:如何從Bash中的JSON對象提取數據?

{"app_versions":[{"version":"16125","shortversion":"4.4.0","title":"App 1","timestamp":1377277516,"appsize":46110031,"mandatory":false,"minimum_os_version":"6.0","device_family":"iPhone/iPod","id":22,"app_id":25196,"download_url":"https://rink.hockeyapp.net/apps/b5dc72777668ca5716aa6aec8237058f/app_versions/22","status":2,"tags":["alpha"]},{"version":"16126","shortversion":"4.4.0","title":"App 1","timestamp":1377177516,"appsize":46330031,"mandatory":false,"minimum_os_version":"6.0","device_family":"iPhone/iPod","id":20,"app_id":25190,"download_url":"https://rink.hockeyapp.net/apps/b5dc72777668ca5716aa6aec8237058f/app_versions/20","status":2,"tags":["alpha"]}

如何從上面的輸出找到的id的最高值,並獲得相關version

+1

哪「外殼」在哪個操作系統? –

+0

你好,謝謝你的回覆。我在Mac OS中使用Bash。 – Rocky

+0

我編輯了你的問題,明確提到JSON。如果您沒有意識到這個輸出是JSON格式,那麼我建議您使用Google的'JSON'來了解格式(及相關工具)。 – ruakh

回答

1

自己張貼的值不是有效的JSON —它在最後—缺少幾個字符,但假設你的實際值有效的,你可以寫這樣的事情:

perl -e \ 
    ' use warnings; 
    use strict; 
    use JSON(); 
    my $highest_id; 
    my $version; 
    foreach my $app_version (@{(JSON::from_json $ARGV[0])->{"app_versions"}}) { 
     my $id = $app_version->{"id"}; 
     if(! defined ($highest_id) || $id > $highest_id) { 
      $highest_id = $id; 
      $version = $app_version->{"version"}; 
     } 
    } 
    print $version; 
    ' \ 
    "$your_variable" 
+0

Ruakh,非常感謝!我會試試這個。 – Rocky