[Python-Dev] Dropping bytes "support" in json

"Martin v. Löwis" martin at v.loewis.de
Tue Apr 14 04:40:10 CEST 2009

> Below is a basic CGI application that assumes that json module works
> with str, not bytes.  How would you write it if the json module does not
> support returning a str?

In a CGI application, you shouldn't be using sys.stdin or print().
Instead, you should be using sys.stdin.buffer (or sys.stdin.buffer.raw),
and sys.stdout.buffer.raw. A CGI script essentially does binary IO;
if you use TextIO, there likely will be bugs (e.g. if you have
attachments of type application/octet-stream).

> print("Content-Type: application/json; charset=utf-8")
> input_object = json.loads(sys.stdin.read())
> output_object = do_some_work(input_object)
> print(json.dumps(output_object))
> print()

out = sys.stdout.buffer.raw
out.write(b"Content-Type: application/json; charset=utf-8\n\n")
input_object = json.loads(sys.stdin.buffer.raw.read())
output_object = do_some_work(input_object)

> What's the benefit of preventing users from getting a str out if that's
> what they want?

If they really want it, there is no benefit from preventing them.
I'm just puzzled why they want it, and what possible applications
might be where they want it. Perhaps they misunderstand something
when they think they want it.


More information about the Python-Dev mailing list