[英]Get the value of specific JSON element in Python
我是Python和JSON的新手,所以如果我聽起來毫無頭緒,我很抱歉。 我從Google Translate API獲得以下結果,並想要解析“translatedText”的值:
{
"data": {
"translations": [
{
"translatedText": "Toute votre base sont appartiennent à nous"
}
]
}
}
使用以下命令將此響應存儲為字符串:
response = urllib2.urlopen(translateUrl)
translateResponse = response.read()
所以是的,我想做的就是獲取翻譯后的文本並將其存儲在變量中。 我搜索過Python Docs,但它看起來很混亂,似乎並不認為JSON存儲為一個簡單的字符串而不是一些超酷的JSON對象。
您可以使用Python> = 2.6中的json
模塊將文本解析為對象:
>>> 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!'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.