json

package module
v0.0.0-...-4e744a1 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2014 License: BSD-2-Clause, BSD-3-Clause Imports: 9 Imported by: 0

README

This project is a work in progress.

Documentation

Documentation

Overview

Package json provides a JSON scanner and writer.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodeValue

func DecodeValue(s *Scanner) (interface{}, error)

DecodeValue decodes the current scanner value to to Go types as follows:

JSON   Go
null   nil
object map[string]interface{}
array  []interface{}
string string
bolean bool
number NumberValue

Types

type Kind

type Kind int

Kind represents the kind a JSON document element.

const (
	// Null represents a JSON null.
	Null Kind = iota

	// Bool represents a JSON bool.
	Bool

	// String represents a JSON string.
	String

	// Number represents a JSON number.
	Number

	// Array represents the start of a JSON array.
	Array

	// Object represents the start of a JSON object.
	Object

	// End represents the end of an object or array.
	End
)

func (Kind) String

func (k Kind) String() string

type NumberValue

type NumberValue string

A NumberValue represents a JSON number literal.

func (NumberValue) Float64

func (n NumberValue) Float64() (float64, error)

Float64 returns the number as a float64.

func (NumberValue) Int

func (n NumberValue) Int() (int, error)

Int returns the number as an int.

func (NumberValue) Int64

func (n NumberValue) Int64() (int64, error)

Int64 returns the number as an int64.

func (NumberValue) String

func (n NumberValue) String() string

String returns the literal text of the number.

func (NumberValue) Uint

func (n NumberValue) Uint() (uint, error)

Uint returns the number as an uint.

func (NumberValue) Uint64

func (n NumberValue) Uint64() (uint64, error)

Uint64 returns the number as an uint64.

type Scanner

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

Scanner reads a JSON document from an io.Reader. Successive calls to the Scan method step through the elements of the document as follows:

element = Null | Bool | Number | String | object | array
array = Array element* End
object = Object element* End

Scanning stops unrecoverably at EOF, the first I/O error, or a syntax error. When a scan stops, the reader may have advanced arbitrarily far past the last token.

When scanning strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD.

Example

This example shows how to decode a JSON value to a tree of maps and slices.

package main

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/garyburd/json"
)

const jsonText = `
[
    {
        "name": "redigo",
        "keywords": ["database", "redis"],
        "imports": 10
    },
    {
        "name": "mgo",
        "keywords": ["database", "mongodb"],
        "imports": 22
    }
]
`

func decodeValue(s *json.Scanner) (interface{}, error) {
	switch s.Kind() {
	case json.Number:
		return strconv.ParseFloat(string(s.Value()), 64)
	case json.String:
		return string(s.Value()), nil
	case json.Array:
		v := []interface{}{}
		n := s.NestingLevel()
		for s.ScanAtLevel(n) {
			subv, err := decodeValue(s)
			if err != nil {
				return v, err
			}
			v = append(v, subv)
		}
		return v, s.Err()
	case json.Object:
		v := make(map[string]interface{})
		n := s.NestingLevel()
		for s.ScanAtLevel(n) {
			name := string(s.Name())
			subv, err := decodeValue(s)
			if err != nil {
				return v, err
			}
			v[name] = subv
		}
		return v, s.Err()
	case json.Bool:
		return s.Value()[0] == 't', nil
	case json.Null:
		return nil, nil
	default:
		return nil, fmt.Errorf("unexpected %v", s.Kind())
	}
}

// This example shows how to decode a JSON value to a tree of maps and slices.
func main() {

	s := json.NewScanner(strings.NewReader(jsonText))

	if !s.Scan() {
		fmt.Printf("error %v\n", s.Err())
		return
	}

	v, err := decodeValue(s)
	if err != nil {
		fmt.Printf("error %v\n", err)
		return
	}

	s.Scan()
	if s.Err() != nil {
		fmt.Printf("error %v\n", s.Err())
		return
	}

	fmt.Println(v)

}
Output:

[map[name:redigo keywords:[database redis] imports:10] map[name:mgo keywords:[database mongodb] imports:22]]

func NewScanner

func NewScanner(rd io.Reader) *Scanner

NewScanner allocates and initializes a new scanner.

func (*Scanner) AllowMultple

func (s *Scanner) AllowMultple()

AllowMultple enables scanning multiple JSON values. If this method is not called, then the scanner expects to find exactly one JSON value.

func (*Scanner) Err

func (s *Scanner) Err() error

Err returns the first non-EOF error that was encountered by the Scanner.

func (*Scanner) Kind

func (s *Scanner) Kind() Kind

Kind returns the kind of the current value.

func (*Scanner) Name

func (s *Scanner) Name() []byte

Name returns the object member name of the current value. The underlying array may point to data that will be overwritten by a subsequent call to Scan.

func (*Scanner) NestingLevel

func (s *Scanner) NestingLevel() int

NestingLevel returns the scanner's current nesting level for objects and array.

func (*Scanner) Scan

func (s *Scanner) Scan() bool

Scan advances the Scanner to the next element, which will then be available through the Kind and Value methods. Scan returns false if there are no more elements in the input or an error is encountered. The Err method returns the error if any.

func (*Scanner) ScanAtLevel

func (s *Scanner) ScanAtLevel(nestingLevel int) bool

ScanAtLevel advances to the next element at the current nesting level, possibly skipping over nested elements. ScanAtLevel returns false at the End element for the current level or if an error is encountered.

func (*Scanner) Value

func (s *Scanner) Value() []byte

Value returns the bytes of the current string or number value. The underlying array may point to data that will be overwritten by a subsequent call to Scan.

type SyntaxError

type SyntaxError struct {
	Pos int
	// contains filtered or unexported fields
}

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

type Writer

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

func NewWriter

func NewWriter(w io.Writer) *Writer

func (*Writer) Bool

func (w *Writer) Bool(b bool) error

func (*Writer) EndArray

func (w *Writer) EndArray() error

func (*Writer) EndObject

func (w *Writer) EndObject() error

func (*Writer) Err

func (w *Writer) Err() error

func (*Writer) Float

func (w *Writer) Float(f float64) error

func (*Writer) Int

func (w *Writer) Int(i int64) error

func (*Writer) Name

func (w *Writer) Name(name string) error

func (*Writer) QuotedInt

func (w *Writer) QuotedInt(i int64) error

func (*Writer) QuotedUint

func (w *Writer) QuotedUint(u uint64) error

func (*Writer) StartArray

func (w *Writer) StartArray() error

func (*Writer) StartObject

func (w *Writer) StartObject() error

func (*Writer) String

func (w *Writer) String(s string) error

func (*Writer) StringBytes

func (w *Writer) StringBytes(p []byte) error

func (*Writer) Uint

func (w *Writer) Uint(u uint64) error

Jump to

Keyboard shortcuts

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