gpt4 book ai didi

python - 将 Ruby 中的 json 响应移植到 Python

转载 作者:行者123 更新时间:2023-12-01 09:19:53 29 4
gpt4 key购买 nike

嘿,我制作了一个利用 Ruby 中的 JSON API 响应的程序,我想将其移植到 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

无论如何,我可以使用 requests 或 json 模块将此代码移植到 Python 中?我尝试过但惨败

根据请求;我已经尝试过:

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 字典获取变量所需的任何内容。

关于python - 将 Ruby 中的 json 响应移植到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50881690/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com