问题描述
:抱歉,我第一次没有足够详细地解释,因为我有点想自己解决其余的问题,但最终我变得更加困惑
我有一个小问题.我想利用网站的API JSON响应
I have a small problem.I wanted to take advantage of a website's API JSON response
{
"Class": {
"Id": 1948237,
"family": "nature",
"Timestamp": 941439
},
"Subtitles": [
{
"Id":151398,
"Content":"Tree",
"Language":"en"
},
{
"Id":151399,
"Content":"Bush,
"Language":"en"
}
]
}
所以我想用每行字幕的组合字符串打印URL,并用换行符分隔
So I'd like to print the url with a combined string of each line of subtitles, seperated by newlines
我设法在Ruby中这样做:
And I manage to do so in Ruby like this:
def get_word
r = HTTParty.get('https://example.com/api/new')
# Check if the request had a valid response.
if r.code == 200
json = r.parsed_response
# Extract the family and timestamp from the API response.
_, family, timestamp = json["Class"].values
# Build a proper URL
image_url = "https://example.com/image/" + family + "/" + timestamp.to_s
# Combine each line of subtitles into one string, seperated by newlines.
word = json["Subtitles"].map{|subtitle| subtitle["Content"]}.join("\n")
return image_url, word
end
end
但是现在我需要将其移植到python上,因为我对python很糟糕,所以我似乎还无法弄清楚.
However now I need to port this to python and because I'm terrible at python I can't really seem to figure it out.
我使用的是请求而不是HTTParty,因为我认为这是最好的选择.我尝试这样做:
I'm using requests instead of HTTParty as I think it's the best equivalent.I tried doing this:
def get_word():
r = requests.request('GET', 'https://example.com/api/new')
if r.status_code == 200:
json = requests.Response
# [DOESN'T WORK] Extract the family and timestamp from the API response.
_, family, timestamp = json["Class"].values
# Build a proper URL
image_url = "https://example.com/image/" + family + "/" + timestamp.to_s
# Combine each line of subtitles into one string, seperated by newlines.
word = "\n".join(subtitle["Content"] for subtitle in json["Subtitles"])
print (image_url + '\n' + word)
get_word()
但是,我在提取JSON响应并合并行方面陷入困境
However I get stuck at extracting the JSON response and combining the lines
推荐答案
您可能需要将传入的json转换为python字典
You might need to convert the incoming json to python dictionary
假设这是您的答复
#convert to dict
import json
json_data = json.loads(response)
# print content
for a_subtitle in response['Subtitles']:
print(a_subtitle['content'])
# extract family and timestamp
family = json_data["Class"]["family"]
timestamp = json_data["Class"]["Timestamp"]
image_url = "https://example.com/image/" + family + "/" + str(timestamp)
这篇关于将JSON响应从Ruby映射到Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!