将 JSON 响应从 Ruby 映射到 Python

Map JSON response from Ruby to 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 方面很糟糕,所以我似乎无法弄清楚。

我正在使用 requests 而不是 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 字典

假设这是您的回应

response = {"Subtitles": ...}

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