Search code examples
pythonjsonrubypython-3.xcode-conversion

Map JSON response from Ruby to Python


[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


Solution

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