HTTPResponse object-JSON object must be str, not & #39; bytes & #39;, httpresponsejson

Source: Internet
Author: User
Tags nexmo

HTTPResponse object-JSON object must be str, not 'bytes ', httpresponsejson

Http://stackoverflow.com/questions/24069197/httpresponse-object-json-object-must-be-str-not-bytes

 

HTTPResponse object-JSON object must be str, not 'bytes'
Up vote17down votefavorite7

I 've been trying to update a small Python library called libpynexmo to work with Python 3.

I 've been stuck on this function:

def send_request_json(self, request):    url = request    req =  urllib.request.Request(url=url)    req.add_header('Accept', 'application/json')    try:        return json.load(urllib.request.urlopen(req))    except ValueError:        return False

When it gets to this, json responds:

TypeError: the JSON object must be str, not 'bytes'

I read in a few places thatjson.loadYou shoshould pass objects (In this caseHTTPResponseObject) with.read()Attached, but it doesn' t work onHTTPResponseObjects.

I'm at a loss as to where to go with this next, but being that my entire 1500 line script is freshly converted to Python 3, I don't feel like going back to 2.7.

Json python-3.x python-3.4 nexmo
Using improve this question Edited Aug 7'14 at 4: 01Emrakul3, 73152659 Asked Jun 5' 14 at 19: 59Chevron132129
 
5  
See here for a solution: stackoverflow.com/questions/6862770 /... -Dano Jun 5' 14 at 20:03
 
Did you try passing it through 2to3? -Zmo Jun 5' 14 at 20:03
 
@ Zmo-Did it manually so I cocould learn more.-Chevron Jun 5' 14
 
@ Dano-Found that link earlier, but was unable to make his workaround apply to my situation. I am unable to use. readall () on my HTTPResponse object. -Chevron Jun 5' 14 at 20:26
2  
@ Chevron, if you're trying to convert the json request object, then use this: json. loads (request. b. Sort ody. decode ('utf-8')-Anshuman Biswas May 28 '15
Show1More comment
4 Answersactiveoldestvotes
Up vote13down voteaccepted

I recently wrote a small function to send Nexmo messages. unless you need the full functionality of the libpynexmo code, this shoshould do the job for you. and if you want to continue overhauling libpynexmo, just copy this code. the key is utf8 encoding.

If you want to send any other fields with your message, the full documentation for what you can include with a nexmo outbound message is here

Python 3.4 tested Nexmo outbound (JSON ):

def nexmo_sendsms(api_key, api_secret, sender, receiver, body):    """    Sends a message using Nexmo.    :param api_key: Nexmo provided api key    :param api_secret: Nexmo provided secrety key    :param sender: The number used to send the message    :param receiver: The number the message is addressed to    :param body: The message body    :return: Returns the msgid received back from Nexmo after message has been sent.    """    msg = {        'api_key': api_key,        'api_secret': api_secret,        'from': sender,        'to': receiver,        'text': body    }    nexmo_url = 'https://rest.nexmo.com/sms/json'    data = urllib.parse.urlencode(msg)    binary_data = data.encode('utf8')    req = urllib.request.Request(nexmo_url, binary_data)    response = urllib.request.urlopen(req)    result = json.loads(response.readall().decode('utf-8'))    return result['messages'][0]['message-id']
Using improve this answer Edited Jun 29 '15 at 20: 51aereaux3161617 Answered Jun 6'14 at 1: 01miR393413
  Add a comment
Up vote30down vote

Facing the same problem I solve it using decode ()

...rawreply = connection.getresponse().read()reply = json.loads(rawreply.decode())
Using improve this answer Answered Jul 1 '14 at 18: 41costas309123
 
13  
Can you explain why this is necessary? -Skaz Jun 26' 15
Add a comment
Up vote5down vote

I met the problem as well and now it pass

import jsonimport urllib.request as urimport urllib.parse as parhtml = ur.urlopen(url).read()print(type(html))data = json.loads(html.decode('utf-8'))

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.