如何在python中选择特定的json元素

时间:2015-07-17 19:49:42

标签: python json

我无法弄清楚如何在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"
        }
      ]
    }
  ]
}

如何选择密钥为MOBILE的网址?

谢谢!

2 个答案:

答案 0 :(得分:6)

  • 首先,使用json.loadsjson.load
  • 将您的JSON文档转换为python对象
  • 其次,循环浏览“urls”字典,查找有问题的项目

例如:

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

答案 1 :(得分:0)

我认为应该这样做。

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)