jsonarray

package module
v0.0.0-...-cd5ab76 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 20, 2014 License: MIT Imports: 5 Imported by: 0

README

jsonarray -- Streaming decoder for JSON arrays

Go library for decoding very large or streaming JSON arrays.

Many streaming JSON APIs give you newline-separated JSON. That's easy to parse, just keep calling json.Decoder.Decode.

Sometimes, streaming APIs, and especially JSON databases, just return a very large JSON array as their result. This is not as easy to handle. jsonarray makes it easy.

(If the large array isn't the outermost JSON object, that's still harder to get right. Ideas for API that can handle that are welcome.)

Use the Go import path

github.com/tv42/jsonarray

Documentation at http://godoc.org/github.com/tv42/jsonarray

Documentation

Overview

Example
package main

import (
	"fmt"
	"io"
	"strings"
	"testing/iotest"

	"github.com/tv42/jsonarray"
)

func main() {
	// simulate streaming by serving reads one byte at a time
	stream := iotest.OneByteReader(
		strings.NewReader(`[{"Greeting": "hell"},{"Greeting": "o, w"},{"Greeting": "orld"}]`),
	)

	type Message struct {
		Greeting string
	}
	dec := jsonarray.NewDecoder(stream)
	for {
		var msg Message
		if err := dec.Decode(&msg); err != nil {
			if err == io.EOF {
				break
			}
			fmt.Printf("decode error: %v\n", err)
			return
		}
		fmt.Printf("%s", msg.Greeting)
	}
	fmt.Printf("\nbye!\n")

}
Output:

hello, world
bye!

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

A Decoder reads and decodes JSON array items from an input stream.

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a new decoder that reads items of a JSON array from r. Only one item is held in memory at a time, and items are decoded as soon as they are completed, without waiting for the whole array.

func (*Decoder) Decode

func (d *Decoder) Decode(v interface{}) error

Decode unmarshals the next item in the array.

On reaching the end of the array, Decode returns io.EOF. This does not mean that the underlying stream would have reached EOF.

If EOF is seen before the JSON array closes, returns io.ErrUnexpectedEOF.

type ErrNotArray

type ErrNotArray struct {
	Bad byte
}

ErrNotArray is the type of an error returned when the stream did not contain a JSON array.

func (*ErrNotArray) Error

func (n *ErrNotArray) Error() string

type ErrNotCommaSeparated

type ErrNotCommaSeparated struct {
	Bad byte
}

ErrNotCommaSeparated is the type of an error returned when the array items in the stream were not comma separated.

func (*ErrNotCommaSeparated) Error

func (n *ErrNotCommaSeparated) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL