Is there a streaming API for JSON?

Viewed 75175

Is DOM the only way to parse JSON?

11 Answers

Some JSON parsers do offer incremental ("streaming") parser; for Java, at least following parsers from json.org page offer such an interface:

(in addition to Software Monkey's parser referred to by another answer)

Actually, it is kind of odd that so many JSON parsers do NOT offer this simple low-level interface -- after all, they already need to implement low-level parsing, so why not expose it.

EDIT (June 2011): Gson too has its own streaming API (with gson 1.6)

By DOM, I assume you mean that the parser reads an entire document at once before you can work with it. Note that saying DOM tends to imply XML, these days, but IMO that is not really an accurate inference.

So, in answer to your questions - "Yes", there are streaming API's and "No", DOM is not the only way. That said, processing a JSON document as a stream is often problematic in that many objects are not simple field/value pairs, but contain other objects as values, which you need to parse to process, and this tends to end up a recursive thing. But for simple messages you can do useful things with a stream/event based parser.

I have written a pull-event parser for JSON (it was one class, about 700 lines). But most of the others I have seen are document oriented. One of the layers I have built on top of my parser is a document reader, which took about 30 LOC. I have only ever used my parser in practice as a document loader (for the above reason).

I am sure if you search the net you will find pull and push based parsers for JSON.

EDIT: I have posted the parser to my site for download. A working compilable class and a complete example are included.

EDIT2: You'll also want to look at the JSON website.

If you are looking specifically for Python, then ijson claims to support it. However, it is only a parser, so I didn't come across anything for Python that can generate json as a stream.

For C++ there is rapidjson that claims to support both parsing and generation in a streaming manner.

Answering the question title: YAJL a JSON parser library in C:

YAJL remembers all state required to support restarting parsing. This allows parsing to occur incrementally as data is read off a disk or network.

So I guess using yajl to parse JSON can be considered as processing stream of data.

In reply to your 2nd question, no, many languages have JSON parsers. PHP, Java, C, Ruby and many others. Just Google for the language of your choice plus "JSON parser".

Related