如何在python中选择特定的json元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31483655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:04:49 来源:igfitidea点击:
how to select specific json element in python
提问by NCS
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 对象中选择特定元素,也无法向 google 提供搜索词组。
This is my JSON
这是我的 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"
}
]
}
]
}
how can I select the URL where the key is MOBILE?
如何选择密钥为 MOBILE 的 URL?
thanks!
谢谢!
采纳答案by Rob?
- 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
- 首先,使用
json.loads
或将您的 JSON 文档转换为 python 对象json.load
- 其次,遍历“urls”字典查找有问题的项目
For example:
例如:
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
回答by Maddy
Something like this I believe should do the trick.
我相信这样的事情应该可以解决问题。
first = {"a": 1, "b": 2, "c": 3,, "d": 4, "e": }
second = {"b": 3, "c": 4, "d": 5, "e": 6, "f": 7}
values = {"a","b","c"}
first.update((key, val) for (key, val) in second.items() if key in values)