want to print the value of a key - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: want to print the value of a key (/thread-1720.html) |
want to print the value of a key - johnkennykumar - Jan-22-2017 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: 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
RE: want to print the value of a key - snippsat - Jan-22-2017 >>> 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.0I 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. RE: want to print the value of a key - johnkennykumar - Jan-23-2017 thanks a ton..i could get the output and could understand what was happening.. |