Werberth Lins
Werberth Lins

Reputation: 200

How to parse this json object into Python?

I'm working with requests, and I got stucked, because I'm changing my source. Thing is, when I request the object to the website, it returns the following json object:

[
{
"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"
}
]

And I want to change the "file_url" value from "http:\/\/gelbooru.com\/images\/ca\/48\/ca4860af9e3be43b1d23b823af607be4.jpg"

to

"http://gelbooru.com/images/ca/48/ca4860af9e3be43b1d23b823af607be4.jpg" so I'll be able to use the website fully by calling it on my program's builder. How do I do that? Thanks in Advance.

Upvotes: 0

Views: 109

Answers (1)

furas
furas

Reputation: 142889

requests can automatically convert JSON data to python dictionary/list

r = request.get(...)

data = r.json()

and then you have access

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

and you will see that there is no \/ because it was converted to correct text.


Example with standard json module which is used by requests internally.

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'] )

Upvotes: 2

Related Questions