2016-05-14 12 views
13

Sto scrivendo uno script per automatizzare la generazione di dati per una demo e ho bisogno di serializzare in un JSON alcuni dati. Parte di questi dati è l'immagine, così ho codificato in Base64, ma quando provo a fare funzionare il mio script ottengo:dati Serialize in JSON un Base64

Traceback (most recent call last): 
    File "lazyAutomationScript.py", line 113, in <module> 
    json.dump(out_dict, outfile) 
    File "/usr/lib/python3.4/json/__init__.py", line 178, in dump 
    for chunk in iterable: 
    File "/usr/lib/python3.4/json/encoder.py", line 422, in _iterencode 
    yield from _iterencode_dict(o, _current_indent_level) 
    File "/usr/lib/python3.4/json/encoder.py", line 396, in _iterencode_dict 
    yield from chunks 
    File "/usr/lib/python3.4/json/encoder.py", line 396, in _iterencode_dict 
    yield from chunks 
    File "/usr/lib/python3.4/json/encoder.py", line 429, in _iterencode 
    o = _default(o) 
    File "/usr/lib/python3.4/json/encoder.py", line 173, in default 
    raise TypeError(repr(o) + " is not JSON serializable") 
    TypeError: b'iVBORw0KGgoAAAANSUhEUgAADWcAABRACAYAAABf7ZytAAAABGdB... 
    ... 
    BF2jhLaJNmRwAAAAAElFTkSuQmCC' is not JSON serializable 

Per quanto ne so, con codifica Base64 qualunque-(un'immagine PNG, in questo caso) è solo una stringa, quindi dovrebbe porre problemi alla serializzazione. Cosa mi manca?

risposta

21

È necessario essere attenti circa i tipi di dati.

Se si legge un immagine binaria, si ottiene byte. Se codi questi byte in base64, ottieni di nuovo ... byte! (Vedere la documentazione sul b64encode)

JSON non può gestire byte prime, è per questo che si ottiene l'errore.

ho appena scritto alcuni esempi, con i commenti, spero che aiuta:

from base64 import b64encode 
from json import dumps 

ENCODING = 'utf-8' 
IMAGE_NAME = 'spam.jpg' 
JSON_NAME = 'output.json' 

# first: reading the binary stuff 
# note the 'rb' flag 
# result: bytes 
with open(IMAGE_NAME, 'rb') as open_file: 
    byte_content = open_file.read() 

# second: base64 encode read data 
# result: bytes (again) 
base64_bytes = b64encode(byte_content) 

# third: decode these bytes to text 
# result: string (in utf-8) 
base64_string = base64_bytes.decode(ENCODING) 

# optional: doing stuff with the data 
# result here: some dict 
raw_data = {IMAGE_NAME: base64_string} 

# now: encoding the data to json 
# result: string 
json_data = dumps(raw_data, indent=2) 

# finally: writing the json string to disk 
# note the 'w' flag, no 'b' needed as we deal with text here 
with open(JSON_NAME, 'w') as another_open_file: 
    another_open_file.write(json_data) 
+0

Ho avuto un problema simile quando ero utilizzare Gmail API per inviare e-mail con questa azione specifica 'ritorno { 'crudo': base64.urlsafe_b64encode (Message.as_string())} '. @spky Grazie per la tua risposta! – InamTaj

+1

Sto facendo lo stesso per il file excel, tutto sta accadendo correttamente ma il file scritto sul disco è corrotto, non può essere aperto normalmente –