Enrico Zini: Streaming JSON objects with python
Streaming JSON objects with python
Dear Lazyweb,
Suppose I'd like to create an HTTP service that gives you a looong list of JSON
objects. For example, one JSON object for every package in
Debian.
One way I could do that is to just transfer a big, dozens of megabytes JSON
array with one element per package. With the standard
json module in python,
this requires the client to buffer all the data in memory for decoding, as the
JSON result would be something like this:
[
info for package 1 ,
info for package 2 ,
...dozens of megabytes...
info for package 30000 ,
...
]
However, it would be reasonable to engineer things so that the client can
process packages one at a time, as they are produced. This can dramatically
reduce client memory usage, as well as remove a large latency between the
start of the request and the start of processing.
One trivial idea would be to just send JSON objects one after the other, and
sort of call load multiple
times.
It doesn't work:
import json
from cStringIO import StringIO
a = StringIO()
json.dump( 1:3 , a)
json.dump( 2:4 , a)
a.reset()
print a.getvalue()
print json.load(a)
gives:
$ python z1.py
"1": 3 "2": 4
Traceback (most recent call last):
File "z1.py", line 8, in <module>
print json.load(a)
File "/usr/lib/python2.6/json/__init__.py", line 267, in load
parse_constant=parse_constant, **kw)
File "/usr/lib/python2.6/json/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.6/json/decoder.py", line 322, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 8 - line 1 column 16 (char 8 - 16)
And the json module documentation
does not provide any way of telling the "stream" decoder to just stop parsing
after the first valid object.
An alternative can be to use chunked transfer
encoding and transfer
each JSON object in a separate HTTP chunk. It would add the overhead of a
little HTTP header per JSON object, which could be significant when generating
lots of small JSON objects, but it would be an implementation that strictly
follows HTTP and JSON standards to the letter in a clean way.
Except:
- How do you stream HTTP chunks in WSGI? The WSGI specification's only mention of chunks is that if you produce a result as a generator of "chunks", they are just sent one after the other (effectively, concatenated) in the response stream.
- How do you read and process one chunk at a time with urllib/urllib2? I searched on Google but I only found people in tears.
we built a streaming JSON app as a part of our platform. However, we
didn't stream a single JSON object as that was a bit cumbersome. When
having syntax like:
[
<json-obj1>,
<json-obj2>,
....
<json-objN>
]
The reader has some problems. Should it read the whole stream to find
the closing bracket ] even if the stream would me tens of megabytes?
Should it try to split on , and parse single objects? What if the
objects contain , so should there be some regexp magic?
We ended up streaming separate JSON objects separated by newlines
(\n). This way the reader can read until hitting \n or end of stream
and then split the result on newlines. The new stream looked like
this:
<json-obj1>\n
<json-obj2>\n
...
<json-objN>\n
This way we could efficiently stream hundreds of thousands of JSON
objects from server to client without reserving a load of memory. For
the WSGI part how to do this, the best would probably to do a
generator that would yield a single JSON object with the newline (we
didn't use WSGI back then). Reading can be done using any reader
capable of handling streams. We used pycurl for reading, but I can't
really recommend it as it is way too complicated for a simple task
like this :p
Hopefully this helps!
This means that if the client has no access to a JSON reader that supports a
stream of concatenated toplevel objects, they can still trivially code it on
top of any JSON library. This means that working clients can be written based
just on Squeeze's python standard library. That's what I'm going to do; I'll
probably implement it as a separate 'jsons' output format for DDE, because
producing a JSON response with multiple toplevel obejcts somehow breaks the
JSON standard.
Thanks to all who provided this excellent information!
Whilst my philosophy with mobile phones has always been "if it can make and
receive calls and SMSes, it's good enough for me", the geek in me
occasionally lusts for a smartphone. So I now have an Android phone.
Once you have a smartphone, you need a plan that includes data. Once you've
got that, you realise that your USB mobile internet dongle is somewhat
redundant, as long as you can get your laptop talk through the phone. It
turns out, with Android, it's pretty easy.
First, root your phone. There are a couple of tethering apps that don't
require rooting, but the tradeoff is you end up having to install
proprietary drivers in your laptop, and if I'm going to have a security hole
somewhere, I prefer it to be in my phone, not my laptop. Rooting an Android
phone is trivially easy with
Just say no.
Filed under Debian since this is a Univention system which is based on Debian (still etch, though.) And what specifically annoyed me was today
On a lark, I 
the release team has
There seems to be a
I have finally reached a decision regarding my involvement in the Debian Ruby packaging efforts. I have decided to stop. This has been a very hard decision to make. I have invested huge amounts of time in that work over the years. I still love the language, and will continue to use it on a daily basis for my own developments. I still hope that it will succeed. I know that some people will be disappointed by that decision (and that others will think your work was useless anyway, people should use RVM and rubygems ).
But I also know that I won t be able to push for all the required changes alone. I just don t have the time, nor the motivation. For the record, here are the changes I would have liked to see in the Ruby community.
The core Ruby development community should mature.
Assigning an IP address statically to a host with a given MAC address using ISC dhcpd is quite trivial, one host entry, a hardware ethernet entry and a fixed-address entry and you are up and running.
Last night was the last time I came back from a pub with my clothes
stinking due to tobacco smoke. The Spanish congress has finally approved a
real anti-smoking law which will ban smoking on public areas, with no
exceptions or ways to workaround the ban. Starting on January 2nd, the
Spanish state will be a smoke-free region (or mostly, it seems it'll be
permitted in open-air events like football stadiums or bullrings, and I
don't think that will be a great problem for me, specially the latter).
For years, my intolerance to smoke has been increasing and I'm really
expectant to see the benefits of this law in my habits. After more than 30
years dealing with smoke around us, it's our turn now. I've been speaking
to a few barmans. In general they seem worried this will affect their
business, but I can't see how it will. Spain has a big culture for having
mid-morning almuerzos in bars, and people are not going to give
that up due to not being able to smoke. They will just do it after they
get out, not during the coffee, and that's it. The barmans of the two bars
I visit most are non-smokers, but have to breath the smoke of hundreds of
cigarretes every day, and can't do anything about it. Until tomorrow, when
this will end and everyone will have a right to breath better air. I hope
this kind of legislation continues to be adopted throughout Europe, because
the FOSDEM welcome party is probably the next smoke horror I'll have to face
soonish. :)
It's after Christmas, and the stores are full of Android tablets ranging in quality from mediocre to competent. Obviously, they're also ranging in terms of GPL compliance from "utter failure" to "pretty good". I've written a summary page
(This is part of a series of posts on
DAViCal 0.9.9.4 is now available, along with AWL 0.46.
This is a recommended upgrade with a focus on stability and reliability.
Release notes are on the wiki at