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.
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.
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!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With