Simple Json issue datatype - python

I'm trying to workout this simple json issue in Python but just can't work out where im going wrong. I have tried using json.dumps() but just either get unicode object has no attribute get or str has not attribute get.
heres my code
import urllib2
import json
url = "http://xxxxxxxxxxxxxxxxxxxxxx"
request = urllib2.Request(url)
response = urllib2.urlopen(request)
data = response.read()
js = json.loads(data)
json = json.dumps(js)
for item in json:
#print item['top']['buyorders'][0]["price"]
print item.get('top').get('buyorders')[0].get['price']

Don't do the dump, pass the response directly to json.load() and iterate over the produced python dictionary:
data = json.load(response)
for key, value in data.iteritems():
...

Related

Printing Nested Json API data using Python

I was able to receive the data using an API get request, now I just need help printing a few objects. I'm having trouble because the objects I need are nested pretty deeply. Objects I need:
-cve ID
-url ref
-description
-severity
json page: https://services.nvd.nist.gov/rest/json/cve/1.0/CVE-2021-40463/
import requests
import json
import pprint
url = "https://services.nvd.nist.gov/rest/json/cve/1.0/CVE-2021-40463/"
params = {"q": "CVE"}
response = requests.get(url, params)
data = json.loads(response.text)
pprint.pprint (data)
import requests
import json
import pprint
url = "https://services.nvd.nist.gov/rest/json/cve/1.0/CVE-2021-40463/"
params = {"q": "CVE"}
response = requests.get(url, params)
data = json.loads(response.content)
pprint.pprint(data)
response.content will return the content of the response. after than:
cve ID: pprint.pprint(data['result']['CVE_Items'][0]['cve']['CVE_data_meta']['ID'])
url ref: pprint.pprint(data['result']['CVE_Items'][0]['cve']['references']['reference_data'][0]['url'])
description: pprint.pprint(data['result']['CVE_Items'][0]['cve']['description']['description_data'][0]['value'])
severity: pprint.pprint(data['result']['CVE_Items'][0]['impact']['baseMetricV2']['severity'])

PUT method using python3 and urbllib - headers

So I am trying to just receive the data from this json. I to use POST, GET on any link but the link I am currently trying to read. It needs [PUT]. So I wanted to know if I was calling this url correctly via urllib or am I missing something?
Request
{"DataType":"Word","Params":["1234"], "ID":"22"}
Response {
JSON DATA IN HERE
}
I feel like I am doing the PUT method call wrong since it is wrapped around Request{}.
import urllib.request, json
from pprint import pprint
header = {"DataType":"Word","Params":"[1234"]", "ID":"22"}
req = urllib.request.Request(url = "website/api/json.service", headers =
heaer, method = 'PUT')
with urllib.request.urlopen(req) as url:
data = json.loads(url.read(), decode())
pprint(data)
I am able to print json data as long as its anything but PUT. As soon as I get a site with put on it with the following JSON template I get an Internal Error 500. So I assumed it was was my header.
Thank you in advanced!

Python Parse JSON Response from URL

I'm am wanting to get information about my Hue lights using a python program. I am ok with sorting the information once I get it, but I am struggling to load in the JSON info. It is sent as a JSON response. My code is as follows:
import requests
import json
response= requests.get('http://192.168.1.102/api/F5La7UpN6XueJZUts1QdyBBbIU8dEvaT1EZs1Ut0/lights')
data = json.load(response)
print(data)
When this is run, all I get is the error:
in load return loads(fp.read(),
Response' object has no attribute 'read'
The problem is you are passing in the actual response which consists of more than just the content. You need to pull the content out of the response:
import requests
r = requests.get('https://github.com/timeline.json')
print r.text
# The Requests library also comes with a built-in JSON decoder,
# just in case you have to deal with JSON data
import requests
r = requests.get('https://github.com/timeline.json')
print r.json
http://www.pythonforbeginners.com/requests/using-requests-in-python
Looks like it will parse the JSON for you already...
Use response.content to access response content and json.loads method instead of json.load:
data = json.loads(response.content)
print data

Send a string of OCR text to resAPI

I am trying to work with RestfulAPI's on python.
After OCR a pdf, I want to send the text to an restfulAPI to get back retrieve specific words along with their position within the text. I have not manage to send the string of text to the API yet.
Code follows:
import requests
import PyPDF2
import json
url = "http://xxapi.xxapi.org/xxx.util.json"
pdfFileObj = open('/Users/xxx/pdftoOCR.pdf','rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(1) # To try with the text found in the first page
data = {"text": pageObj.extractText()}
data_json = json.dumps(data)
params = {'text':'string'}
r = requests.post(url, data=data_json, params=params)
r1 = json.loads(r.text)
Although I get a response 200 from the request, The data should come in Json format with the need to poll some token URL (Which I don`t know how to do it either) Also I don't think the request is correct as when I paste the token url to the browser I see an empty Json file (No words, no position) even if I know the piece of text I'm trying to send contains the desired words.
Thanks in advance! I work with OS X , python 3.5
Well, many thanks to #Jose.Cordova.Alvear for resolving this issue
import json
import requests
pdf= open('test.pdf','rb')
url = "http://xxapi.xxapi.org/xxx.util.json"
payload = {
'file' :pdf
}
response = requests.post(url, files=payload)
print response.json()

Python 3.4.1 - Reading HTTP Request Data

I'm fairly new to Python and I'm trying to execute a HTTP Request to a URL that returns JSON. The code, I have is:
url = "http://myurl.com/"
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)
data = response.read()
I'm getting an error reading: "'bytes' object has no attribute 'read'". I searched around, but haven't found a solution. Any suggestions?
You may find the requests library easier to use:
import requests
data = requests.get('http://example.com').text
or, if you need the raw, undecoded bytes,
import requests
data = requests.get('http://example.com').content

Categories