将 JSON 响应从 Ruby 映射到 Python



[编辑]:对不起,我第一次没有解释足够详细的内容,因为我想自己弄清楚其余的,但我最终更加困惑

自己我有一个小问题。 我想利用网站的 API JSON 响应

{
"Class": {
"Id": 1948237,
"family": "nature",
"Timestamp": 941439
},
"Subtitles":    [
{
"Id":151398,
"Content":"Tree",
"Language":"en"
},
{
"Id":151399,
"Content":"Bush,
"Language":"en"
}
]
}

所以我想用每行字幕的组合字符串打印网址,用换行符分隔

我设法在 Ruby 中这样做,就像这样:

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 方面很糟糕,所以我似乎真的无法弄清楚。

我正在使用请求而不是HTTParty,因为我认为它是最好的等价物。 我尝试这样做:

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响应并组合行

Pythonic 的方式是使用列表理解。

Word = "n".join(subtitle["Content"] for subtitle in json["Subtitles"])

您可能需要将传入的 json 转换为 python 字典

假设这是您的回复

响应 = {"字幕": ...}

#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)

最新更新