Эй, я сделал программу, которая использует JSON API-ответ в Ruby, и я хотел бы портировать его на python, но я действительно не знаю, как
Ответ JSON:
{
"Class": {
"Id": 1948237,
"family": "nature",
"Timestamp": 941439
},
"Subtitles": [
{
"Id":151398,
"Content":"Tree",
"Language":"en"
},
{
"Id":151399,
"Content":"Bush,
"Language":"en"
}
]
}
И вот код Ruby:
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
В любом случае, я мог бы переносить этот код на Python с помощью запросов и, возможно, модулей json? Я пробовал, но терпел неудачу
По запросу; что я уже пробовал:
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
Не работает, поскольку я не знаю, как их переносить.
Если вы используете модуль requests
, вы можете вызвать requests.get()
для вызова GET, а затем использовать json()
для получения ответа JSON. Кроме того, вы не должны использовать json
в качестве имени переменной, если вы импортируете модуль json
.
Попробуйте внести следующие изменения в свою функцию:
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
чтобы получить все, что вам нужно для ваших переменных.