将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" } ] } 

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

我设法在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响应和组合行时遇到困难

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

假设这是你的回应

response = {“字幕”:…}

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

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

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