Leonid Romanov
Leonid Romanov

Reputation: 31

Getting JSON error: the JSON object must be str, not 'bytes'

trying to translate a script from Python 2 to 3 in order to make a script to get wheater indication from narodmon.ru to Domiticz/

#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
import urllib.request, urllib.error, urllib.parse
import json
import hashlib
import uuid

api_key = '********'
app_id = str(uuid.getnode())
md5_app_id = hashlib.md5(app_id.encode('utf-8')).hexdigest()
data = {
    'cmd': 'sensorsNearby',
    'uuid': md5_app_id,
    'api_key': api_key,
    'radius': 11,
    'lat': 55.75,
    'lng': 37.62,
    'lang': 'ru'
    }

try:
    request = urllib.request.Request('http://narodmon.ru/api',json.dumps(data).encode("utf-8"))
    response = urllib.request.urlopen(request)
    result = json.loads(response.read())
    print((json.dumps(result, indent=4, sort_keys=True)))
except urllib.error.URLError as e:
    print('HTTP error:', e)
except (ValueError, TypeError) as e:
    print('JSON error:', e)

then get an error

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

Where am I wrong? Thanx a lot

Upvotes: 3

Views: 13215

Answers (1)

chepner
chepner

Reputation: 530960

response.read() returns a bytes object, which is just that: a sequence of bytes. You need to decode it first, because Python doesn't know what the bytes represent.

buf = response.read()
result = json.loads(buf.decode('utf-8'))

Unless you are dealing with a lot of non-ASCII characters, it is easy to confuse a Unicode string with its UTF-8 encoding.

>>> 'foo'
'foo'
>>> 'foo'.encode('utf-8')
b'foo'
>>> 'föö'
'föö'
>>> 'föö'.encode('utf-8')
b'f\xc3\xb6\xc3\xb6'

Upvotes: 7

Related Questions