python - 将 Ruby 中的 json 响应移植到 Python

标签 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

无论如何,我可以使用 requests 或 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 字典获取变量所需的任何内容。

关于python - 将 Ruby 中的 json 响应移植到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50881690/

相关文章:

python - 在 opencv-python 中用颜色填充区域

python-3.6 打印集表达式不按顺序

json - JSON 请求中的哪个 Drupal 8.1.x Rest API 属性控制 Drupal 的文件状态(临时和永久)逻辑?

python - 搜索字典键python

python - 与 pandas 中的 df.diff() 相反

javascript - 如何使用 AngularJS 为每个页面从 JSON 文件加载不同部分的数据?

java - Java中如何检查JsonNode是单个元素还是数组?

ruby-on-rails - 如何替换字符串并保留大写?

ruby-on-rails - ruby 有导出吗?

ruby-on-rails - 带有文件、参数和标题字段的 RSpec Post