如何将Ruby中的JSON响应移植到Python?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (43)

我做了一个利用Ruby中的JSONAPI响应的程序,想把它移植到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

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()
提问于
用户回答回答于

如果你使用的是requests模块,可以调用requests.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

        ...

扫码关注云+社区

领取腾讯云代金券