Marorin
Marorin

Reputation: 167

How to pull information from a Json

I was wondering how to use the requests library to pull the text from a field in a Json? I wouldn't need beautiful soup for that right?

Upvotes: 0

Views: 87

Answers (2)

Alex
Alex

Reputation: 21766

What version of Python are you using ? From 2.6 onwards you can do this:

import json

json_data=open(file_directory).read()

data = json.loads(json_data)
print(data)

Upvotes: 0

Anzel
Anzel

Reputation: 20553

If your response is indeed a json format, you can simply use requests .json() to access the fields, example like this:

import requests

url = 'http://time.jsontest.com/'

r = requests.get(url)
# use .json() for json response data
r.json()
{u'date': u'03-28-2015',
 u'milliseconds_since_epoch': 1427574682933,
 u'time': u'08:31:22 PM'}

# to access the field
r.json()['date']
u'03-28-2015'

This will automatically parse the json response into Python's dictionary:

type(r.json())
dict

You can read more about response.json here.

Alternatively just use Python's json module:

import json

d = json.loads(r.content)

print d['date']
03-28-2015

type(d)
dict

Upvotes: 2

Related Questions