Is there a streaming API for JSON? [closed]

Is DOM the only way to parse JSON?


Solution 1:

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

  • Jackson (pull interface)
  • Json-simple (SAX-style push 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)

Solution 2:

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.

Solution 3:

As stefanB mentioned, http://lloyd.github.com/yajl/ is a C library for stream parsing JSON. There are also many wrappers mentioned on that page for other languages:

  • yajl-ruby - ruby bindings for YAJL
  • yajl-objc - Objective-C bindings for YAJL
  • YAJL IO bindings (for the IO language)
  • Python bindings come in two flavors, py-yajl OR yajl-py
  • yajl-js - node.js bindings (mirrored to github).
  • lua-yajl - lua bindings
  • ooc-yajl - ooc bindings
  • yajl-tcl - tcl bindings

some of them may not allow streaming, but many of them certainly do.