如何将这个json对象解析为Python?

2024-04-19 01:51:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我在处理请求,但我被绊倒了,因为我在改变我的来源。问题是,当我向网站请求对象时,它会返回以下json对象:

[
{
"directory":"ca\/48",
"hash":"ca4860af9e3be43b1d23b823af607be4",
"height":1839,
"id":3461818,
"image":"ca4860af9e3be43b1d23b823af607be4.jpg",
"change":1480968006,
"owner":"danbooru",
"parent_id":null,
"rating":"s",
"sample":true,
"sample_height":1398,
"sample_width":850,
"score":0,
"tags":"1girl breasts cape cleavage defense_of_the_ancients dota_2 green_eyes highres lyralei medium_breasts parted_lips pauldrons red_hair smile solo splashbrush thick_thighs thighs toes",
"width":1118,
 "file_url":"http:\/\/gelbooru.com\/images\/ca\/48\/ca4860af9e3be43b1d23b823af607be4.jpg"
}
]

我想把"file_url"的值改为"http:\/\/gelbooru.com\/images\/ca\/48\/ca4860af9e3be43b1d23b823af607be4.jpg"

"http://gelbooru.com/images/ca/48/ca4860af9e3be43b1d23b823af607be4.jpg" 所以我可以通过调用我的程序的生成器来完全使用这个网站。 我该怎么做? 提前谢谢。你知道吗


Tags: sample对象comidhttp网站widthca
1条回答
网友
1楼 · 发布于 2024-04-19 01:51:29

requests可以自动将JSON数据转换为python字典/列表

r = request.get(...)

data = r.json()

然后你就可以进入了

print( data[0]['file_url'] )

您将看到没有\/,因为它被转换为正确的文本。你知道吗


标准json模块的示例,该模块由requests内部使用。你知道吗

text = '''[
{
"directory":"ca\/48",
"hash":"ca4860af9e3be43b1d23b823af607be4",
"height":1839,
"id":3461818,
"image":"ca4860af9e3be43b1d23b823af607be4.jpg",
"change":1480968006,
"owner":"danbooru",
"parent_id":null,
"rating":"s",
"sample":true,
"sample_height":1398,
"sample_width":850,
"score":0,
"tags":"1girl breasts cape cleavage defense_of_the_ancients dota_2 green_eyes highres lyralei medium_breasts parted_lips pauldrons red_hair smile solo splashbrush thick_thighs thighs toes",
"width":1118,
 "file_url":"http:\/\/gelbooru.com\/images\/ca\/48\/ca4860af9e3be43b1d23b823af607be4.jpg"
}
]'''

import json

data = json.loads(text)

print( data[0]['file_url'] )

相关问题 更多 >