将Ruby中的json响应移植到Python

时间:2018-06-15 19:33:39

标签: python json ruby python-3.x code-conversion

嘿,我制作了一个程序,利用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代码不起作用,因为我不知道如何移植它们。

1 个答案:

答案 0 :(得分:1)

如果您正在使用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字典获取变量所需的任何内容。