Search code examples
arraysjsonpython-3.xfor-loopnested-loops

Iterating over a JSON array


I have the following JSON array;

"json_array": [
    {
        "key": "k1",
        "value": "v1"
    },
    {
        "key": "k2",
        "value": "v2"
    }
]

Need to list values as v1,v2.

Currently, I am able to list the keys and values separately as follows, but as a whole, not separately:

k1:v1 k2:v2

or

k1 k2

or

v1 v2

I was trying to get something like: v1,v2 but I'm not sure how to go about the iteration, like if I just need to print one value either v1 or v2. If someone could help me with the logic in Python 3, that would be really great.

Edited code:

json_array = [
    [
        {
            "key": "k1",
            "value": "v1"
        },
        {
            "key": "k1",
            "value": "v2"
        }
    ],
    [
        {
            "key": "k1",
            "value": "v3"
        },
        {
            "key": "k2",
            "value": "v4"
        }
    ],
    [
        {
            "key": "k2",
            "value": "v5"
        },
        {
            "key": "k3",
            "value": "v6"
        }
    ]
]
itemcount = 0

for item in json_array:
    print(item)
    values = []
    
    for kv in item:
        if 'value' in kv:
                values.append(kv['value'])

    print(', '.join([kv['key']] + values))

Output:

[{'key': 'k1', 'value': 'v1'}, {'key': 'k1', 'value': 'v2'}]
k1, v1, v2
[{'key': 'k1', 'value': 'v3'}, {'key': 'k2', 'value': 'v4'}]
k2, v3, v4
[{'key': 'k2', 'value': 'v5'}, {'key': 'k3', 'value': 'v6'}]
k3, v5, v6

Expected output:

k1, v1, v2, v3
k2, v4, v5
k3, v6

Solution

  • You could do something like this:

    json_array = [
        {
            "key": "k1",
            "value": "v1"
        },
        {
            "key": "k2",
            "value": "v2"
        }
    ]
    
    itemcount = 0
    values = []
    
    for item in json_array:
        print(f'Item => {itemcount}')
        itemcount += 1
        
        if 'value' in item:
                print(f"Value => {item['value']}")
                values.append(item['value'])
    
    print(', '.join(values))
    

    That'll give you output like this:

    Item => 0
    Value => v1
    Item => 1
    Value => v2
    v1, v2
    

    If you just wanted v1, v2 as the output, you could just do this:

    values = []
    
    for item in json_array:
        if 'value' in item:
                values.append(item['value'])
    
    print(', '.join(values))
    

    What are we doing here?

    We loop through each item in the list. Each item is a dictionary. We ask the dictionary if it has 'value' property. If it has, then we add it to a list.

    Finally, we join the list with ', ' separator.

    You can morph this to whatever output you desire. Hope this gets you started.


    EDIT

    What if you have an nested lists/arrays?

    json_array = [
        [
            {
                "key": "k1",
                "value": "v1"
            },
            {
                "key": "k2",
                "value": "v2"
            }
        ],
        [
            {
                "key": "k1",
                "value": "v3"
            },
            {
                "key": "k2",
                "value": "v4"
            }
        ]
    ]
    itemcount = 0
    values = []
    
    for item in json_array:
        print(f'Item => {itemcount}')
        itemcount += 1
        
        for kv in item:
            if 'value' in kv:
                    print(f"Value => {kv['value']}")
                    values.append(kv['value'])
    
    print(', '.join(values))
    

    The result will be:

    Item => 0
    Value => v1
    Value => v2
    Item => 1
    Value => v3
    Value => v4
    v1, v2, v3, v4
    

    EDIT 2

    If you want v1, v2 in one line and v3, v4 in another line

    You could use a slightly modified code to print v1, v2 in one line and v3, v4 in another line.

    json_array = [
        [
            {
                "key": "k1",
                "value": "v1"
            },
            {
                "key": "k2",
                "value": "v2"
            }
        ],
        [
            {
                "key": "k1",
                "value": "v3"
            },
            {
                "key": "k2",
                "value": "v4"
            }
        ]
    ]
    itemcount = 0
    
    for item in json_array:
        print(f'Item => {itemcount}')
        itemcount += 1
        
        values = []
        
        for kv in item:
            if 'value' in kv:
                    print(f"Value => {kv['value']}")
                    values.append(kv['value'])
    
        print(', '.join(values))
    

    The result will be:

    Item => 0
    Value => v1
    Value => v2
    v1, v2
    Item => 1
    Value => v3
    Value => v4
    v3, v4
    

    It seems like OP has figured this out already; great job.


    EDIT 3

    What if we want key, value1, value2, ...?

    json_array = [
        [
            {
                "key": "k1",
                "value": "v1"
            },
            {
                "key": "k1",
                "value": "v2"
            }
        ],
        [
            {
                "key": "k1",
                "value": "v3"
            },
            {
                "key": "k2",
                "value": "v4"
            }
        ],
        [
            {
                "key": "k2",
                "value": "v5"
            },
            {
                "key": "k3",
                "value": "v6"
            }
        ]
    ]
    itemcount = 0
    values = {}
    
    for item in json_array:
        itemcount += 1
        
        for kv in item:
            if kv['key'] not in values:
                values[kv['key']] = []
            
            values[kv['key']].append(kv['value'])
            
    for key in values:
        print(key + ', ' + ', '.join(values[key]))
    

    will result in:

    k1, v1, v2, v3
    k2, v4, v5
    k3, v6