sunil
sunil

Reputation: 85

Parse JSON Data using Shell Scripting

How do I parse the values of the string 'key' from the below json data using shell scripting?

/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"}]}

Example output: SAR-32, SAR-5 so on..

Upvotes: 0

Views: 2698

Answers (3)

Дід Alik
Дід Alik

Reputation: 319

One may use nodejs with Here Documents, for example:

alec@mba ~/project/lnet (master) $ cat /Users/alec/project/lnet/test/rc/05\ Two\ hubs.json
{
  "desc": "This is a configuration file to run the test on all the hubs and leaves that can possibly participate",
  "hubs": { "hub0": "176.37.63.2", "hub1": "10.0.0.10" }
}
alec@mba ~/project/lnet (master) $ runAll() {
>   local conf="$HOME/project/lnet/$1"
>   echo "runAll: using configuration file $conf"
>   local output=$(node <<-EOF_JS
>     const conf = require("$conf")
>     console.log('hub0="' + conf.hubs.hub0 + '"')
> EOF_JS
> )
>   eval "$output"; echo "$hub0"
> }
alec@mba ~/project/lnet (master) $ runAll test/rc/05\ Two\ hubs.json
runAll: using configuration file /Users/alec/project/lnet/test/rc/05 Two hubs.json
176.37.63.2
alec@mba ~/project/lnet (master) $ 

Upvotes: 0

chepner
chepner

Reputation: 532418

Assuming valid JSON like

{
    "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"
        }
    ]
}

you can use the following call to jq:

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

Upvotes: 2

Tim
Tim

Reputation: 2187

You can use grep and cut to do this easily:

[ttucker@localhost ~]$ 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"}]}

[ttucker@localhost ~]$ grep -o '"key":"[^"]*"' /tmp/testjira2 |cut -d'"' -f4
SAR-32
SAR-5

Upvotes: 0

Related Questions