Python Forum
want to print the value of a key
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
want to print the value of a key
#1
import http.client, urllib.request, urllib.parse, urllib.error

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key':'##'
}

params = urllib.parse.urlencode({
    # Request parameters
    'numberOfLanguagesToDetect': '10',
})
body = {
  "documents": [
        {
            "language": "en",
            "id": "1",
            "text": "First document. Hello world."
        }
    ]
}
try:
    conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')
    conn.request("POST", "/text/analytics/v2.0/languages?%s" % params, str(body), headers)
    response = conn.getresponse()
    data = response.read()
      
    print(data)
    #pydict=json.load(data)    
    #print(pydict)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))
from the above code i get json output as:
Output:
runfile('C:/Users/msamu/textanalyse.py', wdir='C:/Users/msamu') b'{"documents":[{"id":"1","detectedLanguages":[{"name":"English","iso6391Name":"en","score":1.0}]}],"errors":[]}'
i want to print the value of the score ie 1.0 but iam not able to do it..i used dumps function to get a python dictionary and and print but its not happening can you please help thanks a ton
Reply
#2
>>> import json 
>>> s = b'{"documents":[{"id":"1","detectedLanguages":[{"name":"English","iso6391Name":"en","score":1.0}]}],"errors":[]}'
>>> data = json.loads(s)
Traceback (most recent call last):
 File "<string>", line 301, in runcode
 File "<interactive input>", line 1, in <module>
 File "C:\Python34\lib\json\__init__.py", line 312, in loads
   s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

>>> # So convert to string
>>> s = s.decode()
>>> data = json.loads(s)
>>> data
{'documents': [{'detectedLanguages': [{'iso6391Name': 'en',
                                       'name': 'English',
                                       'score': 1.0}],
               'id': '1'}],
'errors': []}
# Get score
>>> data['documents'][0]['detectedLanguages'][0]['score']
1.0
I your other post i recommend you to use Requests.
Then you don't need to use json from standard library,or convert from bytes to string.
Reply
#3
thanks a ton..i could get the output and could understand what was happening..
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020