[英]How to extract an attribute from a json response using python
I am using the face++ API, I need to get an attribute from the first request(json_resp) to add it in the second one (json_resp2) 我正在使用face ++ API,我需要从第一个请求(json_resp)获取属性以将其添加到第二个请求(json_resp2)
import requests
json_resp = requests.post( 'https://api- us.faceplusplus.com/facepp/v3/detect',
data = { 'api_key' : 'api key' ,
'api_secret' : 'api secret',
'image_url' : 'http://www.pick-health.com/wp-content/uploads/2013/08/happy-person.jpg' } )
print("Response : ", json_resp.text)
This request outputs: 该请求输出:
Response : {"image_id": "0UqxdZ6b58TaAFxBiujyMA==", "request_id": "1523139597,9f47c376-481b-446f-9fa3-fb49e404437c", "time_used": 327, "faces": [{"face_rectangle": {"width": 126, "top": 130, "left": 261, "height": 126}, "face_token": "2da210ada488fb10b58cdd2cd9eb3801"}]}
响应:{“ image_id”:“ 0UqxdZ6b58TaAFxBiujyMA ==”,“ request_id”:“ 1523139597,9f47c376-481b-446f-9fa3-fb49e404437c”,“ time_used”:327,“ faces”:[{“ face_rectangle”:{“ width “:126,” top“:130,” left“:261,” height“:126},” face_token“:” 2da210ada488fb10b58cdd2cd9eb3801“}]}
I need to access the face_token to pass it to the second request: 我需要访问face_token将其传递给第二个请求:
json_resp2 = requests.post( 'https://api-us.faceplusplus.com/facepp/v3/face/analyze',
data = { 'api_key' : 'api key' ,
'api_secret' : 'api secret',
'face_tokens' : 'json_resp.face_tokens',
'return_landmark':0,
'return_attributes':'emotion'} )
print("Response2 : ", json_resp2.text)
how can I do this please ? 请问我该怎么做?
To get the text string from the response object, you can use json_resp.text
. 要从响应对象获取文本字符串,可以使用
json_resp.text
。 You can then use the json
library to convert this into a dict
, and then extract the field you want: 然后,您可以使用
json
库将其转换为dict
,然后提取所需的字段:
json_resp = requests.post(...) ## Your post request, as written above
node = json.loads(json_resp.text)
face_token = node['faces'][0]['face_token']
Here is the full code (using your snippets above): 这是完整的代码(使用上面的代码段):
import requests
import json
api_key = 'your api key'
api_secret = 'your api secret'
json_resp = requests.post(
'https://api-us.faceplusplus.com/facepp/v3/detect',
data = {
'api_key' : api_key,
'api_secret' : api_secret,
'image_url' : 'http://www.pick-health.com/wp-content/uploads/2013/08/happy-person.jpg'
}
)
node = json.loads(json_resp.text)
face_token = node['faces'][0]['face_token']
json_resp2 = requests.post(
'https://api-us.faceplusplus.com/facepp/v3/face/analyze',
data = {
'api_key' : api_key,
'api_secret' : api_secret,
'face_tokens' : face_token,
'return_landmark' : 0,
'return_attributes' : 'emotion'
}
)
print("Response2 : ", json_resp2.text)
PS: It's a bad idea to post API keys online, since people can run your bill up by using your services. PS:在线发布API密钥是一个坏主意,因为人们可以通过使用您的服务来增加您的账单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.