获取Python中特定JSON元素的值 [英] Get the value of specific JSON element in Python
问题描述
我是Python和JSON的新手,所以如果我听起来一无所知,我们深感抱歉.我从Google Translate API获得以下结果,并想解析出"translatedText"的值:
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()
是的,我要做的就是获取翻译后的文本并将其存储在变量中.我已经搜索过Python文档,但它看起来如此令人困惑,而且似乎没有考虑将JSON存储为简单字符串而不是一些超酷的JSON对象.
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.
推荐答案
您可以使用Python> = 2.6中的json
模块将文本解析为对象:
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!'
这篇关于获取Python中特定JSON元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!