简体   繁体   中英

Count The Number Of Json Key Pairs In A Bash Shell Script

Within a ADO yaml pipeline one of my jobs has a inline script bash shell running. I want to automate a counter being used for a loop later in the script. The counter represents the number of some json embedded key pairs (the value of these key pairs hold variables). Like in most ADO pipelines the variable sheet (it's actually a variable template sheet but that doesn't matter) is stored separately to the pipeline and called on at the start of the yaml pipeline.

{
  "abc": {
    "models": {
      "model1": {
        "a": "x",
        "b": "z"
      },
      "model2": {
        "a": "x",
        "b": "z"
      },
      "model3": {
        "a": "x",
        "b": "z"
      }
    }
  }
}

The desired outcome of this example would be 3 but in the future more models will be added. For context the model names are subject to change - so it's not possible to do something odd like take the last key pair name and split off the number. It would be best if the solution is written in Bash as I would prefer to avoid any complexities.

The only related things I could find and test were:

            modelCount5="$(jq 'abc.models | length' ${{ parameters.variableGroup }})"
            echo $modelCount5
            modelCount6="$(jq '.abc.models | length' ${{ parameters.variableGroup }})"
            echo $modelCount6
            modelCount7="$(jq '$(abc.models) | length' )"
            echo $modelCount7
            modelCount9="$(jq '$(abc.models) | length' ${{ parameters.variableGroup }})"
            echo $modelCount9

They all resulted in complie errors or directory not found errors. Eg:

jq: 1 compile error
or
jq: error: Could not open file CTS: No such file or directory

I have checked the agent running the pipeline and jq has been preinstalled.

Answer

Thankyou all for your help. In the end I did this:

   modelCount="$(jq '.variables.abc.models | length' $(Build.SourcesDirectory)/variables/templates/variables-sheet.jsonc)"   

...and it worked great. It was a matter of configuring my path to the file properly.

You can get the extract the count and store it in a shell variable with the following statement:

modelCount="$(jq '.variables.abc.models | length' path/to/your/file"

length in jq gives you the length of an array. $(…) is command substution and substitutes the command with its output to be used by the parent command line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM