7

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!

5
  • 1
    That's not valid JSON. Please copy-paste the exact JSON text you are working with. Commented Jul 17, 2015 at 19:54
  • First of all, that's not valid JSON. You can use json module which will load it as a dict. Commented Jul 17, 2015 at 19:55
  • Have you read the python manual? In the docs this info is easy to find. Commented Jul 17, 2015 at 19:56
  • sorry guys, new JSON included Commented Jul 17, 2015 at 20:02
  • I don't know why this was marked as duplicate, the question is quite different. The ref question asked how to get the value, when you know the key. This one is more like "select object from list where key= value". Commented Mar 26, 2024 at 14:45

2 Answers 2

20
  • 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
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.