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

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

Printing data in python by parsing json

问题

  1. 我正在尝试获取正确的表示法以解析JSON数据并在Python中打印所需的输出
  2. 这是一个示例JSON文件
  3. 播放信息JSON响应
  4. ```json
  5. {
  6. "id": 111,
  7. "age": 22,
  8. "Hobby": [
  9. {
  10. "List": 1,
  11. "Sev": "medium",
  12. "name": "play 1",
  13. "game": "tennis"
  14. },
  15. {
  16. "List": 2,
  17. "Sev": "high",
  18. "name": "play 2",
  19. "game": "football"
  20. },
  21. {
  22. "List": 2,
  23. "Sev": "high",
  24. "name": "play 3",
  25. "game": "racing"
  26. }
  27. ]
  28. }

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

  1. <details>
  2. <summary>英文:</summary>
  3. I am trying to get the correct notation to parse json data and print the required output in python
  4. here is a sample json file
  5. 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",
}
]

  1. I am looking for python commands to print the outcome of play 2 ie, football from the json file..Appreciate the help.
  2. </details>
  3. # 答案1
  4. **得分**: 0
  5. a = [hobby['game'] for hobby in json['Hobby'] if hobby['name'] == 'play 2']
  6. print(a)
  7. Output:
  8. ['football']
  9. <details>
  10. <summary>英文:</summary>
  11. Maybe this can help you:
  12. json = { &quot;id&quot;: 111, &quot;age&quot;: 22, &quot;Hobby&quot;: [
  13. { &quot;List&quot;: 1, &quot;Sev&quot;: &quot;medium&quot;, &quot;name&quot;: &quot;play 1&quot;, &quot;game&quot;: &quot;tennis&quot;, },
  14. { &quot;List&quot;: 2, &quot;Sev&quot;: &quot;high&quot;, &quot;name&quot;: &quot;play 2&quot;, &quot;game&quot;: &quot;football&quot;, },
  15. { &quot;List&quot;: 2, &quot;Sev&quot;: &quot;high&quot;, &quot;name&quot;: &quot;play 3&quot;, &quot;game&quot;: &quot;racing&quot;, } ]}
  16. a = [hobby[&#39;game&#39;] for hobby in json[&#39;Hobby&#39;] if hobby[&#39;name&#39;] == &#39;play 2&#39;]
  17. print(a)
  18. Output:
  19. [&#39;football&#39;]
  20. </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:

确定