skip to Main Content

I was able to retrieve values for values data1, data2… using data.get function in Python.

data = json.load(file.json)
print(f"##vso[task.setvariable variable=var1;isOutput=true]{data.get('A', {}).get('key1', {})}")

However, I wish to make use of the same technique to retrieve the values X and Y for some particular syntax checking on my json file.

{
    "A": {
        "key1": "data1"
        "key2": "data2",
        "key3": "data3"
    },
    "B": {
        "X": {
            "key4": "data4",
        },
        "Y": {
            "key5": "data5",
        }
    }
}

I tried to use the following but I am also getting the keys key4 and key5 on B.

print(f"##vso[task.setvariable variable=var1;isoutput=true]{data.get('B', {})}")

I only wanted to get the value of X or Y itself and not what is mapped inside.

Can anyone please help? Thanks!

2

Answers


  1. Expanding on @deceze comment:

    keys = list(data.get('B', {}).keys())
    print(f"##vso[task.setvariable variable=var1;isoutput=true]{keys}")
    

    the value of keys would be:

    ['X', 'Y']
    
    Login or Signup to reply.
  2. You’re dealing with a nested dictionary once the JSON has been loaded.

    import json
    
    data_str = """{
        "A": {
            "key1": "data1",
            "key2": "data2",
            "key3": "data3"
        },
        "B": {
            "X": {
                "key4": "data4"
            },
            "Y": {
                "key5": "data5"
            }
        }
    }"""
    
    data = json.loads(data_str)
    
    print("type(data):", type(data))
    
    print("data.keys():", data.keys())
    
    print("type(data['B']):", type(data.get('B', {})))
    
    print("data['B']:", data.get('B', {}))
    
    print("data['B'].keys():", data['B'].keys())
    
    for k in data.get('B', {}).keys():
        print(f"type(data['B']['{k}']):", type(data.get('B', {}).get(k, {})))
        print(f"data['B']['{k}']:", data.get('B', {}).get(k, {}))
    

    Output:

    type(data): <class 'dict'>
    data.keys(): dict_keys(['A', 'B'])
    type(data['B']): <class 'dict'>
    data['B']: {'X': {'key4': 'data4'}, 'Y': {'key5': 'data5'}}
    data['B'].keys(): dict_keys(['X', 'Y'])
    type(data['B']['X']): <class 'dict'>
    data['B']['X']: {'key4': 'data4'}
    type(data['B']['Y']): <class 'dict'>
    data['B']['Y']: {'key5': 'data5'}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search