将 Ruby 中的 json 响应移植到 Python

Porting json response in Ruby to Python

嘿,我制作了一个利用 Ruby 中的 JSON API 响应的程序,我想将其移植到 python,但我不知道真的不知道怎么办

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

无论如何,我可以使用请求和 json 模块将此代码移植到 Python? 我试过但惨败

根据要求;我已经尝试过的:

def get_word():
  r = requests.request('GET', 'https://example.com/api/new')
  if r.status_code == 200:
      # ![DOESN'T WORK]! Extract the family and timestamp from the API 
      json = requests.Response 
      _, family, timestamp = json["Class"].values

      # Build a proper URL
      image_url = "https://example.com/image/" + family + "/" + timestamp

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

响应和 _, family, timestamp = json["Class"].values 代码不起作用,因为我不知道如何移植它们。

如果您正在使用 requests 模块,您可以调用 requests.get() 进行 GET 调用,然后使用 json() 获取 JSON 响应。此外,如果要导入 json 模块,则不应使用 json 作为变量名。

尝试在您的函数中进行以下更改:

def get_word():
    r = requests.get("https://example.com/api/new")
    if r.status_code == 200:
        # Extract the family and timestamp from the API 
        json_response = r.json()

        # json_response will now be a dictionary that you can simply use

        ...

并使用 json_response 字典获取变量所需的任何内容。