遍历JSON数组

huangapple go评论73阅读模式
英文:

Iterating over a JSON array

问题

以下是您提供的代码的翻译部分:

我有以下的JSON数组;
```json
"json_array": [
    {
        "key": "k1",
        "value": "v1"
    },
    {
        "key": "k2",
        "value": "v2"
    }
]

需要将值列出为v1,v2。

目前,我能够分别列出键和值,但不能分开列出:

k1:v1
k2:v2

k1
k2

v1
v2

我尝试获得类似于:
v1,v2 但我不确定如何进行迭代,就像如果我只需要打印一个值,要么是v1要么是v2。如果有人能帮我解决Python 3中的逻辑,那将非常好。

编辑后的代码:

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))

输出:

[{'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

期望输出:

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


如果您需要进一步的帮助,请告诉我。

<details>
<summary>英文:</summary>

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&#39;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 = [
        [
            {
                &quot;key&quot;: &quot;k1&quot;,
                &quot;value&quot;: &quot;v1&quot;
            },
            {
                &quot;key&quot;: &quot;k1&quot;,
                &quot;value&quot;: &quot;v2&quot;
            }
        ],
        [
            {
                &quot;key&quot;: &quot;k1&quot;,
                &quot;value&quot;: &quot;v3&quot;
            },
            {
                &quot;key&quot;: &quot;k2&quot;,
                &quot;value&quot;: &quot;v4&quot;
            }
        ],
        [
            {
                &quot;key&quot;: &quot;k2&quot;,
                &quot;value&quot;: &quot;v5&quot;
            },
            {
                &quot;key&quot;: &quot;k3&quot;,
                &quot;value&quot;: &quot;v6&quot;
            }
        ]
    ]
    itemcount = 0
    
    for item in json_array:
        print(item)
        values = []
        
        for kv in item:
            if &#39;value&#39; in kv:
                    values.append(kv[&#39;value&#39;])
    
        print(&#39;, &#39;.join([kv[&#39;key&#39;]] + values))

Output:

    [{&#39;key&#39;: &#39;k1&#39;, &#39;value&#39;: &#39;v1&#39;}, {&#39;key&#39;: &#39;k1&#39;, &#39;value&#39;: &#39;v2&#39;}]
    k1, v1, v2
    [{&#39;key&#39;: &#39;k1&#39;, &#39;value&#39;: &#39;v3&#39;}, {&#39;key&#39;: &#39;k2&#39;, &#39;value&#39;: &#39;v4&#39;}]
    k2, v3, v4
    [{&#39;key&#39;: &#39;k2&#39;, &#39;value&#39;: &#39;v5&#39;}, {&#39;key&#39;: &#39;k3&#39;, &#39;value&#39;: &#39;v6&#39;}]
    k3, v5, v6

Expected output:

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

</details>


# 答案1
**得分**: 1

这是您要翻译的代码部分:

```python
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))

这将为您提供以下输出:

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

如果您只想要v1, v2作为输出,可以使用以下代码:

values = []

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

print(', '.join(values))

我们在这里的操作是遍历列表中的每个项。每个项都是一个字典。我们询问字典是否有'value'属性。如果有,我们将其添加到列表中。

最后,我们使用', '分隔符连接列表。

您可以根据需要修改这个代码来获得所需的输出。希望这能帮助您入门。

英文:

You could do something like this:

json_array = [
    {
        &quot;key&quot;: &quot;k1&quot;,
        &quot;value&quot;: &quot;v1&quot;
    },
    {
        &quot;key&quot;: &quot;k2&quot;,
        &quot;value&quot;: &quot;v2&quot;
    }
]

itemcount = 0
values = []

for item in json_array:
    print(f&#39;Item =&gt; {itemcount}&#39;)
    itemcount += 1
    
    if &#39;value&#39; in item:
            print(f&quot;Value =&gt; {item[&#39;value&#39;]}&quot;)
            values.append(item[&#39;value&#39;])

print(&#39;, &#39;.join(values))

That'll give you output like this:

Item =&gt; 0
Value =&gt; v1
Item =&gt; 1
Value =&gt; v2
v1, v2

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

values = []

for item in json_array:
    if &#39;value&#39; in item:
            values.append(item[&#39;value&#39;])

print(&#39;, &#39;.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 = [
    [
        {
            &quot;key&quot;: &quot;k1&quot;,
            &quot;value&quot;: &quot;v1&quot;
        },
        {
            &quot;key&quot;: &quot;k2&quot;,
            &quot;value&quot;: &quot;v2&quot;
        }
    ],
    [
        {
            &quot;key&quot;: &quot;k1&quot;,
            &quot;value&quot;: &quot;v3&quot;
        },
        {
            &quot;key&quot;: &quot;k2&quot;,
            &quot;value&quot;: &quot;v4&quot;
        }
    ]
]
itemcount = 0
values = []

for item in json_array:
    print(f&#39;Item =&gt; {itemcount}&#39;)
    itemcount += 1
    
    for kv in item:
        if &#39;value&#39; in kv:
                print(f&quot;Value =&gt; {kv[&#39;value&#39;]}&quot;)
                values.append(kv[&#39;value&#39;])

print(&#39;, &#39;.join(values))

The result will be:

Item =&gt; 0
Value =&gt; v1
Value =&gt; v2
Item =&gt; 1
Value =&gt; v3
Value =&gt; 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 = [
    [
        {
            &quot;key&quot;: &quot;k1&quot;,
            &quot;value&quot;: &quot;v1&quot;
        },
        {
            &quot;key&quot;: &quot;k2&quot;,
            &quot;value&quot;: &quot;v2&quot;
        }
    ],
    [
        {
            &quot;key&quot;: &quot;k1&quot;,
            &quot;value&quot;: &quot;v3&quot;
        },
        {
            &quot;key&quot;: &quot;k2&quot;,
            &quot;value&quot;: &quot;v4&quot;
        }
    ]
]
itemcount = 0

for item in json_array:
    print(f&#39;Item =&gt; {itemcount}&#39;)
    itemcount += 1
    
    values = []
    
    for kv in item:
        if &#39;value&#39; in kv:
                print(f&quot;Value =&gt; {kv[&#39;value&#39;]}&quot;)
                values.append(kv[&#39;value&#39;])

    print(&#39;, &#39;.join(values))

The result will be:

Item =&gt; 0
Value =&gt; v1
Value =&gt; v2
v1, v2
Item =&gt; 1
Value =&gt; v3
Value =&gt; 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 = [
    [
        {
            &quot;key&quot;: &quot;k1&quot;,
            &quot;value&quot;: &quot;v1&quot;
        },
        {
            &quot;key&quot;: &quot;k1&quot;,
            &quot;value&quot;: &quot;v2&quot;
        }
    ],
    [
        {
            &quot;key&quot;: &quot;k1&quot;,
            &quot;value&quot;: &quot;v3&quot;
        },
        {
            &quot;key&quot;: &quot;k2&quot;,
            &quot;value&quot;: &quot;v4&quot;
        }
    ],
    [
        {
            &quot;key&quot;: &quot;k2&quot;,
            &quot;value&quot;: &quot;v5&quot;
        },
        {
            &quot;key&quot;: &quot;k3&quot;,
            &quot;value&quot;: &quot;v6&quot;
        }
    ]
]
itemcount = 0
values = {}

for item in json_array:
    itemcount += 1
    
    for kv in item:
        if kv[&#39;key&#39;] not in values:
            values[kv[&#39;key&#39;]] = []
        
        values[kv[&#39;key&#39;]].append(kv[&#39;value&#39;])
        
for key in values:
    print(key + &#39;, &#39; + &#39;, &#39;.join(values[key]))

will result in:

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

huangapple
  • 本文由 发表于 2023年6月26日 23:33:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76558172.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定