-2

I have below json and using awk to print value of concurrency but it is not giving any output

{
    "GlanceImages.list_images": [
        {
            "runner": {
                "type": "constant",
                "times": 10,
                "concurrency": 1
            },
            "context": {
                "users": {
                    "tenants": 2,
                    "users_per_tenant": 2
                },
                "images": {
                    "image_url": "http://download.cirros-cloud.net/0.3.5/cirros-0.3.5-x86_64-disk.img",
                    "disk_format": "qcow2",
                    "container_format": "bare",
                    "images_per_tenant": 4
                }
            },
            "sla": {
                "failure_rate": {
                    "max": 0
                }
            }
        }
    ]
}

Using awk

echo xyz.json | awk -F: '$1=="concurrency" {print $2}'

It doesnt give any output, what could be the issue. Ultimately I have to read multiple files and sum up all the values of concurrency and finally print the ultimate sum

Saurabh Arora
  • 377
  • 2
  • 4
  • 11
  • 1
    Why aren't you using a JSON parser like jq? – Inian Jul 07 '20 at 16:02
  • Not an expert in jq but I tried and it gives output as null `jq '.runner.concurrency' xyz.json` `null` – Saurabh Arora Jul 07 '20 at 16:10
  • To complete the question: as is mentioned in earlier (deleted) answers, the user has no access to `jq`. A bulletproof `awk` solution is requested. – kvantour Jul 08 '20 at 09:27
  • Would this question not be an excellent duplicate? [Parsing JSON with Unix tools](https://stackoverflow.com/questions/1955505/parsing-json-with-unix-tools). I'm very convinced you have access to python? – kvantour Jul 08 '20 at 09:30

1 Answers1

4

another fragile script

$ awk '$1=="\"concurrency\":"{print $2}' file

if you have multiple matches you want to aggregate

$ awk '$1=="\"concurrency\":"{sum+=$2} END{print sum}' file
karakfa
  • 66,216
  • 7
  • 41
  • 56
  • this works thanks!!! but just wanted to check, if there is a better way to write below code (ignore variable names, it is just an example) `p=0 while read -r line do var=$(awk '$1=="\"concurrency\":"{print $2}' $line) echo $var p=$(( $p+$var )) echo "p is $p" echo "$line" done < "$input"` – Saurabh Arora Jul 07 '20 at 17:09
  • @SaurabhArora Yes but [chameleon questions](https://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions) are strongly discouraged. Accept the answer you got to the question you asked and then ask a new question if you have one. – Ed Morton Jul 07 '20 at 19:06
  • Thanks @Karakfa that answers the question I had at first place but second answer would depend on case to case, since I have multiple files and need to add `concurrency` values across different files so this will not work, anyhow that answers the query I had. thanks!!! – Saurabh Arora Jul 08 '20 at 06:33