0

[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

3
  • Can you give an example of what that would look like from the data set you provided for those who don't know Ruby? Commented Jun 15, 2018 at 18:05
  • What is your desired output? Commented Jun 15, 2018 at 18:05
  • Sorry I didn't explain enough, I kind of wanted to figure the rest out for myself but I ended up confusing myself even more. The desired output is by example: https://example.com/image/nature/941439 Tree bush Of course there won't always be only two subtitles Commented Jun 15, 2018 at 18:48

2 Answers 2

2

The Pythonic way is to use a list comprehension.

Word = "\n".join(subtitle["Content"] for subtitle in json["Subtitles"])
Sign up to request clarification or add additional context in comments.

Comments

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 Comments

That's interesting and I thank you for your help, however another of my problem is that I don't know how I could convert the ruby code: json = r.parsed_response _, family, timestamp = json["Class"].values to Python
You will again parse the json_data. family = json_data["Class"]["family"] timestamp = json_data["Class"]["Timestamp"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.