Вопрос

I have read questions about including files content in JSON. The question are about binary file. The solution is to encode the content (base64 for example). In case I would include plain text file (that may contain json xml or anything else but only text).

I already know about multipart/format-data. I'm working with Python/Java on Server/Client side.

So my question do I need to encode my file or no? Please explain why.

Это было полезно?

Решение

Plain text can be put into a JSON string just fine. Use a JSON library (like Python's ]json module](https://docs.python.org/2/library/json.html)) to ensure the data is escaped correctly:

import json

with open('some_text_file.txt') as txtfile:
    data = {'filedata': txtfile.read()}

json_data = json.dumps(data)

In Python 2, if you have non-ASCII text you may need to decode the text to Unicode explicitly to ensure it is encoded with the right codec when encoding to JSON again.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top