Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the value of specific JSON element in Python

Tags:

python

json

I'm new to Python and JSON, so I'm sorry if I sound clueless. I'm getting the following result from the Google Translate API and want to parse out the value of "translatedText":

{
 "data": {
  "translations": [
   {
    "translatedText": "Toute votre base sont appartiennent à nous"
   }
  ]
 }
}

This response is simply stored as a string using this:

response = urllib2.urlopen(translateUrl)
translateResponse = response.read()

So yeah, all I want to do is get the translated text and store it in a variable. I've searched the Python Docs but it seems so confusing and doesn't seem to consider JSON stored as a simple string rather than some super cool JSON object.

like image 567
Matt Avatar asked Jan 15 '11 01:01

Matt


People also ask

How can I get specific data from JSON?

Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.


1 Answers

You can parse the text into an object using the json module in Python >= 2.6:

>>> import json
>>> translation = json.loads("""{
...  "data": {
...   "translations": [
...    {
...     "translatedText": "Toute votre base sont appartiennent  nous"
...    },
...    {
...     "translate": "¡Qué bien!"
...    }
...   ]
...  }
... }
... """)
>>> translation
{u'data': {u'translations': [{u'translatedText': u'Toute votre base sont appartiennent  nous'}]}}
>>> translation[u'data'][u'translations'][0][u'translatedText']
u'Toute votre base sont appartiennent  nous'
>>> translation[u'data'][u'translations'][1][u'translate']
u'¡Qué bien!'
like image 102
fmark Avatar answered Oct 27 '22 00:10

fmark