我是 Python 和 JSON 的新手,所以如果我听起来一无所知,我很抱歉。我从 Google Translate API 得到以下结果,并想解析出“translatedText”的值:
{
"data": {
"translations": [
{
"translatedText": "Toute votre base sont appartiennent à nous"
}
]
}
}
这个响应简单地存储为一个字符串,使用这个:
response = urllib2.urlopen(translateUrl)
translateResponse = response.read()
是的,我只想获取翻译后的文本并将其存储在一个变量中。我搜索了 Python 文档,但它看起来很困惑,而且似乎没有考虑将 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!'
关于python - 在 Python 中获取特定 JSON 元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4697626/