0

I have a JSON response that looks like:

{u'AllowExistingAttachmentToBeOverwritten': False,
 u'Name': u'Go-Daddy.pdf', 
 u'AttachmentData': u'JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9DcmVhdG9yIChNb3ppbGxhLzUuMCBcKFdpbmR...
u'ItemIdAttachedTo': 91198711,
u'Description': u''}

How do I convert it to a PDF file?

I tried:

with open(fileName, 'wb') as f:
    f.write(result['AttachmentData']) 
    f.close()

also tried:

with open(fileName, 'wb') as f:
    f.write(result['AttachmentData'].encode()) 
    f.close()

but in both cases the file were created but Adobe could not open the file.

2

2 Answers 2

1

To fully answer your question as soon as you receive data from json file is encoded in BASE64 UTF8 in most cases.To be able to get content of it or save it to the disk it should be BASE64DECODED.

To Replicate your situation following website was used (te get BASE64ENCODED PDF) : http://jsfiddle.net/eliseosoto/JHQnk/

As per suggestion of @eran-s where pdf_base64 is pdf received from json response.

import base64
pdf_base64 = 'JVBERi0xLj...' 
with open('test.pdf', 'wb') as f:
    f.write(base64.b64decode(pdf_base64))
    f.close()

This solution was tested and works like charm.

Please refer to link below for some more information. Embedding a File Attachment in JSON Object

1
  • @eran-s : I think you may need to call decode function instead of encode as per Zebromatz. try changing the line to f.write( base64.b64decode(result['AttachmentData']) )
    – Hara
    Commented Jun 14, 2017 at 8:30
0

Just adding to the @Zebromatz. You just try to decode the file data to base64. Also validate while sending in json whether you are encoding with base64. Your possible code would be as follows.

import base64

# bla bla bla
# bla bla bla

with open(fileName, 'wb') as f:
    f.write( base64.b64decode(result['AttachmentData']) )
    f.close()

See if this would works.

1
  • Thank you for the detailed answer. Worked like a charm.
    – Eran S
    Commented Jun 15, 2017 at 1:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.