write bytes64 in json python

Solutions on MaxInterview for write bytes64 in json python by the best coders in the world

showing results for - "write bytes64 in json python"
Paloma
04 Nov 2020
1from base64 import b64encode
2from json import dumps
3
4ENCODING = 'utf-8'
5IMAGE_NAME = 'spam.jpg'
6JSON_NAME = 'output.json'
7
8# first: reading the binary stuff
9# note the 'rb' flag
10# result: bytes
11with open(IMAGE_NAME, 'rb') as open_file:
12    byte_content = open_file.read()
13
14# second: base64 encode read data
15# result: bytes (again)
16base64_bytes = b64encode(byte_content)
17
18# third: decode these bytes to text
19# result: string (in utf-8)
20base64_string = base64_bytes.decode(ENCODING)
21
22# optional: doing stuff with the data
23# result here: some dict
24raw_data = {IMAGE_NAME: base64_string}
25
26# now: encoding the data to json
27# result: string
28json_data = dumps(raw_data, indent=2)
29
30# finally: writing the json string to disk
31# note the 'w' flag, no 'b' needed as we deal with text here
32with open(JSON_NAME, 'w') as another_open_file:
33    another_open_file.write(json_data)