-1

I'm having trouble to get ID from json code that mutch a specific value in such array I explain: I have this code json:

{
  "results": [
    {
      "TAB": "bleu",
      "exp": [
        {
          "A": "NOT_PROTECTED",
          "B": [
            "500",
            "600"
          ],
          "C": false
        }
      ],
      "ID": "000041"
    },
    {
      "TAB": "rouge",
      "exp": [
        {
          "A": "PROTECTED",
          "B": [
            "700",
            "800"
          ],
          "C": true
        }
      ],
      "ID": "000042"
    }
  ]
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574

1 Answers1

1

I'm assuming the question is how you access the values in Ansible, since it has the ansible tag.

You can use the map filter in Ansible to access the values like so: (where your json is in the some_json variable.)

- debug:
    msg: "{{ some_json.results | map(attribute='ID') | list }}"

results:

ok: [localhost] => {  
    "msg": [          
        "000041",     
        "000042"      
    ]                 
}                     

If you want to do it with json_query/jmespath (As the question is also tagged with json_query and jmespath) then it would be like this:

- debug:
    msg: "{{ some_json.results | json_query('[*].ID') | list }}"
ok: [localhost] => {
    "msg": [        
        "000041",   
        "000042"    
    ]               
}                   

That being said, I do prefer the map method myself since it does not require any extra dependencies where as json_query requires jmespath to be installed.

gardar
  • 75
  • 4
  • actually it's not what I want exactly, your code is juste get all IDs, but what I want is to get an ID that mutch B[0] = 500 , like in this example, I want to get as result : 00041 because it's B[0] = 500 – Mohamed Bouraoui Nov 03 '21 at 13:01