Json

在 Bash 中解析 .json

  • July 12, 2021

有一個json我試圖解析的文件,podfox以允許我以“友好”的方式重命名下載的文件。json這是我正在使用的片段:

{
   "episodes": [
       {
            "title": "Hired and Fired by Little Richard and Jimi\u2019s first trip on LSD",
            "url": "https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW2392375869.mp3",
            "downloaded": true,
            "listened": false,
            "published": 1582203660.0
       },
       {
            "title": "Stolen Cars, Broken Taboos, and the Search for Billy Davis",
            "url": "https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW5134475908.mp3",
            "downloaded": true,
            "listened": false,
            "published": 1581598860.0
       },
   ]
   "shortname": "27 Club",
   "title": "27 Club",
   "url": "https://feeds.megaphone.fm/HSW5142951139"
}

我正在嘗試基於urlgettitle並將其傳遞給bash. 我可以(在大多數情況下)使用grep,但我知道這jq是一種更好的方法,我只是無法弄清楚使其jq工作的語法。

這適用於命令行上的 grep:grep -B 1 HSW2392375869.mp3 < feed.json | grep "title" | cut -d"\"" -f4但似乎它是一個潛在的容易出錯的解決方案。

當我嘗試時:jq -c '.["episodes"].url'外殼無限期地掛起。我不需要在jq這裡使用,所以任何允許我搜尋url並返回(最終)值的方法publishedtitle可以。

實際上首先需要過濾.episodes然後是內部數組

jq ".episodes | .[0]" jsonfile
{
 "title": "Hired and Fired by Little Richard and Jimi’s first trip on LSD",
 "url": "https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW2392375869.mp3",
 "downloaded": true,
 "listened": false,
 "published": 1582203660
}

標題:

jq ".episodes| .[0].title" jsonfile
"Hired and Fired by Little Richard and Jimi’s first trip on LSD"

發表:

jq ".episodes| .[0].published" jsonfile
1582203660

基於url值的查詢

jq '.episodes | .[] | select(.url=="https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW2392375869.mp3").title' jsonfile    
"Hired and Fired by Little Richard and Jimi’s first trip on LSD"    

jq '.episodes | .[] | select(.url=="https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW2392375869.mp3").published' jsonfile
1582203660

引用自:https://unix.stackexchange.com/questions/593244