首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将Ruby中的json响应移植到Python

将Ruby中的json响应移植到Python
EN

Stack Overflow用户
提问于 2018-06-16 03:33:39
回答 1查看 72关注 0票数 1

嘿,我用Ruby编写了一个利用JSON API响应的程序,我想把它移植到python上,但我真的不知道怎么做

JSON响应:

代码语言:javascript
复制
{
    "Class": {
        "Id": 1948237,
        "family": "nature",
        "Timestamp": 941439
    },
    "Subtitles":    [
      {
        "Id":151398,
        "Content":"Tree",
        "Language":"en"
      },
      {
        "Id":151399,
        "Content":"Bush,
        "Language":"en"
      }
    ]
}

下面是Ruby代码:

代码语言:javascript
复制
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?我试过了,但惨遭失败。

每个请求;我已经尝试过的内容:

代码语言:javascript
复制
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代码无法工作,因为我不知道如何移植它们。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-16 04:22:25

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

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

代码语言:javascript
复制
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字典获取您的变量所需的任何内容。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50881690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档