Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select specific json element in python [duplicate]

Tags:

python

json

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!

like image 835
NCS Avatar asked Jul 17 '15 19:07

NCS


1 Answers

  • 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
like image 63
Robᵩ Avatar answered Nov 08 '22 20:11

Robᵩ