通过解析JSON在Python中打印数据。

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

Printing data in python by parsing json

问题

我正在尝试获取正确的表示法以解析JSON数据并在Python中打印所需的输出

这是一个示例JSON文件

播放信息JSON响应
```json
{
  "id": 111,
  "age": 22,
  "Hobby": [
    {
      "List": 1,
      "Sev": "medium",
      "name": "play 1",
      "game": "tennis"
    },
    {
      "List": 2,
      "Sev": "high",
      "name": "play 2",
      "game": "football"
    },
    {
      "List": 2,
      "Sev": "high",
      "name": "play 3",
      "game": "racing"
    }
  ]
}

我正在寻找在Python中打印play 2的结果(即来自JSON文件的football)的命令。感谢帮助。


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

I am trying to get the correct notation to parse json data and print the required output in python

here is a sample json file

Play info Json Response:

{
"id": 111,
"age": 22,
"Hobby": [
{
"List": 1,
"Sev": "medium",
"name": "play 1",
"game": "tennis",
},
{
"List": 2,
"Sev": "high",
"name": "play 2",
"game": "football",
},
{
"List": 2,
"Sev": "high",
"name": "play 3",
"game": "racing",
}
]


I am looking for python commands to print the outcome of play 2 ie, football from the json file..Appreciate the help.


</details>


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

a = [hobby['game'] for hobby in json['Hobby'] if hobby['name'] == 'play 2']
print(a)

Output:

['football']

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

Maybe this can help you:

    json = { &quot;id&quot;: 111, &quot;age&quot;: 22, &quot;Hobby&quot;: [ 
        { &quot;List&quot;: 1, &quot;Sev&quot;: &quot;medium&quot;, &quot;name&quot;: &quot;play 1&quot;, &quot;game&quot;: &quot;tennis&quot;, }, 
        { &quot;List&quot;: 2, &quot;Sev&quot;: &quot;high&quot;, &quot;name&quot;: &quot;play 2&quot;, &quot;game&quot;: &quot;football&quot;, }, 
        { &quot;List&quot;: 2, &quot;Sev&quot;: &quot;high&quot;, &quot;name&quot;: &quot;play 3&quot;, &quot;game&quot;: &quot;racing&quot;, } ]}
    
    
    a = [hobby[&#39;game&#39;] for hobby in json[&#39;Hobby&#39;] if hobby[&#39;name&#39;] == &#39;play 2&#39;]
    print(a)

Output:

    [&#39;football&#39;]

</details>



huangapple
  • 本文由 发表于 2023年6月19日 20:53:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76506838.html
匿名

发表评论

匿名网友

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

确定