如何在python中选择特定的json元素 [英] how to select specific json element in python
本文介绍了如何在python中选择特定的json元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道如何在JSON对象中选择特定元素,也无法为Google提出搜索词组.
I can't figure out how to select a specific element in a JSON object, and I cant come up with a search phrase to google.
这是我的JSON
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
如何选择键为"MOBILE"的URL?
how can I select the URL where the key is MOBILE?
谢谢!
推荐答案
- 首先,使用
json.loads
或json.load
将JSON文档转换为python对象
- 第二,在"urls"字典中循环查找有问题的项目
- First, convert your JSON document into a python object using
json.loads
orjson.load
- Second, loop through the "urls" dictionary looking for the item in question
例如:
import json
json_document='''
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
'''
python_obj = json.loads(json_document)
for url in python_obj["products"][0]["urls"]:
if url["key"] == "MOBILE":
value = url["value"]
break
else:
# Some default action
print "No url found"
value = "http://www.url.com"
print "Value:", value
这篇关于如何在python中选择特定的json元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文