2016-12-06 119 views
0

如何使用shell腳本從下面的json數據解析字符串'key'的值?使用Shell腳本解析JSON數據

/Users/local/Documents/testjira:{"expand":"schema","names","startAt":"0","maxResults":"50","total":"2","issues":[{"expand":"operations","editmeta","changelog","transitions","renderedFields","id":"56392","self":"https://website.com/jira/rest/api/latest/issue/50342","key":"SAR-32"},{"expand":"operations","editmeta","changelog","transitions","renderedFields","id":"49799","self":"https://website.com/jira/rest/api/latest/issue/19720","key":"SAR-5"}]} 

輸出示例: SAR-32,SAR-5等..

+3

使用合適'json'解析像我使用上述命令['jq'](https://stedolan.github.io/jq/) – Inian

回答

-1

可以使用grepcut和要做到這一點很容易:

[[email protected] ~]$ cat /tmp/testjira2 
{"expand":"schema","names","startAt":"0","maxResults":"50","total":"2","issues":[{"expand":"operations","editmeta","changelog","transitions","renderedFields","id":"56392","self":"https://website.com/jira/rest/api/latest/issue/50342","key":"SAR-32"},{"expand":"operations","editmeta","changelog","transitions","renderedFields","id":"49799","self":"https://website.com/jira/rest/api/latest/issue/19720","key":"SAR-5"}]} 

[[email protected] ~]$ grep -o '"key":"[^"]*"' /tmp/testjira2 |cut -d'"' -f4 
SAR-32 
SAR-5 
+0

工具,但它沒有顯示任何輸出。我使用了「grep -o'鍵的命令:[--A-Z0-9] *'/ Users/local/Documents/jira | cut -d:-f2」 – sunil

+0

您使用的是什麼版本的'grep'? 'grep -V'另外,你確定你的數據與你的樣本數據相匹配嗎? – varlogtim

+0

是的,我相信數據是一樣的。 grep版本 - 'grep(GNU grep)2.20' – sunil

1

假設有效的JSON像

{ 
    "expand":["schema", "names"], 
    "startAt":"0", 
    "maxResults":"50", 
    "total":"2", 
    "issues":[ 
     { 
      "expand":["operations","editmeta","changelog","transitions","renderedFields"], 
      "id":"56392", 
      "self":"https://website.com/jira/rest/api/latest/issue/50342", 
      "key":"SAR-32" 
     }, 
     { 
      "expand":["operations","editmeta","changelog","transitions","renderedFields"], 
      "id":"49799", 
      "self":"https://website.com/jira/rest/api/latest/issue/19720", 
      "key":"SAR-5" 
     } 
    ] 
} 

您可以使用以下調用jq

$ jq -r '.issues[] | .key' tmp.json 
SAR-32 
SAR-5