Search code examples
pythonjsonrubypython-3.xcode-conversion

Porting json response in Ruby to Python


Hey I made a program that takes advantage of a JSON API response in Ruby and I'd like to port it to python, but I don't really know how

JSON response:

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

And here's the Ruby code:

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

Anyway I could port this code to Python using requests and maybe json modules? I tried but failed miserably

Per request; what I've already tried:

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()

The response and _, family, timestamp = json["Class"].values code don't work as I don't know how to port them.


Solution

  • If you're using the requests module, you can call requests.get() to make a GET call, and then use json() to get the JSON response. Also, you shouldn't be using json as a variable name if you're importing the json module.

    Try making the following changes in your function:

    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
    
            ...
    

    And use the json_response dictionary to get anything you need for your variables.