Python Forum
How can I add files to GitLab with `python-gitlab`?
Thread Rating:
  • 2 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I add files to GitLab with `python-gitlab`?
#3
JSON format only supports Unicode strings.
you can decode to string(which is Unicode by default in Python 3),be using decode() or decode('ascii') as Base64 encodes bytes to ASCII-only bytes.
Error:
>>> import base64
>>> import json
>>> 
>>> place = base64.b64encode(open('foo.txt', "rb").read())
>>> place
b'aGVsbG8gd29ybGQNCg0K'
>>> type(place)
<class 'bytes'>

>>> d = {}
>>> d['name'] = place
>>> json.dumps(d)
Traceback (most recent call last):
  File "<string>", line 428, in runcode
  File "<interactive input>", line 1, in <module>
  File "C:\Python37\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python37\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python37\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Python37\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable
Fix:
>>> import base64
>>> import json
>>> 
>>> place = base64.b64encode(open('foo.txt', "rb").read()).decode() # Or decode('ascii')
>>> type(place)
<class 'str'>
>>> d = {}
>>> d['name'] = place
>>> json.dumps(d)
'{"name": "aGVsbG8gd29ybGQNCg0K"}'
Reply


Messages In This Thread
RE: How can I add files to GitLab with `python-gitlab`? - by snippsat - Jul-02-2018, 11:51 AM

Forum Jump:

User Panel Messages

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