Map JSON response from Ruby to Python

巧了我就是萌 提交于 2019-12-11 14:39:57

问题


[EDIT]: Sorry I didn't explain in enough details the first time as I kind of wanted to figure the rest out for myself, but I ended up confusing myself even more

I have a small problem. I wanted to take advantage of a website's API JSON response

{
    "Class": {
        "Id": 1948237,
        "family": "nature",
        "Timestamp": 941439
    },
    "Subtitles":    [
      {
        "Id":151398,
        "Content":"Tree",
        "Language":"en"
      },
      {
        "Id":151399,
        "Content":"Bush,
        "Language":"en"
      }
    ]
}

So I'd like to print the url with a combined string of each line of subtitles, seperated by newlines

And I manage to do so in Ruby like this:

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

However now I need to port this to python and because I'm terrible at python I can't really seem to figure it out.

I'm using requests instead of HTTParty as I think it's the best equivalent. I tried doing this:

def get_word():
  r = requests.request('GET', 'https://example.com/api/new')
  if r.status_code == 200:
      json = requests.Response
      # [DOESN'T WORK] 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 = "\n".join(subtitle["Content"] for subtitle in json["Subtitles"])
      print (image_url + '\n' + word)

get_word()

However I get stuck at extracting the JSON response and combining the lines


回答1:


You might need to convert the incoming json to python dictionary

Assuming this is your response

response = {"Subtitles": ...}

#convert to dict
import json
json_data = json.loads(response)
# print content
for a_subtitle in response['Subtitles']:
    print(a_subtitle['content'])

# extract family and timestamp
family = json_data["Class"]["family"]
timestamp = json_data["Class"]["Timestamp"]
image_url = "https://example.com/image/" + family + "/" + str(timestamp)



回答2:


The Pythonic way is to use a list comprehension.

Word = "\n".join(subtitle["Content"] for subtitle in json["Subtitles"])


来源:https://stackoverflow.com/questions/50880647/map-json-response-from-ruby-to-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!