how to select specific json element in python [dup

2020-06-24 06:43发布

问题:

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.

This is my 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?

thanks!

回答1:

  • First, convert your JSON document into a python object using json.loads or json.load
  • Second, loop through the "urls" dictionary looking for the item in question

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


回答2:

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)