开发者

Get the value of specific JSON element in Python

I'm new to Python and JSON, so I'm sorry if I sound cluel开发者_StackOverflow中文版ess. 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.


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!'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜