libconfig

package module
Version: v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2021 License: MIT Imports: 12 Imported by: 0

README

libconfig

A golang language library for reading libconfig file

Note

  • Modified based on valyala/fastjson, fastjson is a json library.
  • Refer to scan character mode to realize parsing configuration file.
  • Implement the function of parsing configuration file similar to hyperrealm/libconfig, that is a C/C++ library.
  • The project is still in the development stage, please do not use it in the production environment.

support

  • skip # comment
  • skip // comment
  • skip /* */ comment
  • scalarvalue
  • Hexadecimal data
  • big int
  • array
  • group
  • list
  • @include

example

parse bytes
data := []byte(`foo="bar"; baz=1234;`)
foo := libconfig.GetString(data, "foo")
fmt.Println("foo = %s\n", foo)
parse from file
data, err := ioutil.ReadFile("testdata/demo.cfg")
if err != nil {
    log.Fatal("read config file error: ", err.Error())
}

fmt.Printf("version = %s\n", libconfig.GetString(data, "version"))
parse with object

from strings

var p libconfig.Parser

v, err := p.Parse(`foo="bar"; baz=1234;`)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("foo = %s\n", v.Get("foo").String())
fmt.Printf("foo = %s\n", string(v.GetStringBytes("foo")))

from file

var p libconfig.Parser

v, err := p.ParseFile("testdata/example4.cfg")
if err != nil {
    log.Fatal(err)
}

fmt.Printf("books[0].title=%s\n", v.GetArray("books")[0].GetStringBytes("title"))

parse element

scalarvalue、Hexadecimal data、big int

data := []byte(`foo="bar"; baz=1234; bigint=9223372036854775807L; float=1.0; bool=false;`)

// string
fmt.Printf("foo = %s\n", libconfig.GetString(data, "foo"))

// bytes
fmt.Printf("foo = %s\n", libconfig.GetBytes(data, "foo"))

// int
fmt.Printf("baz = %d\n", libconfig.GetInt(data, "baz"))

// hex value
fmt.Printf("baz = %s\n", libconfig.GetHex(data, "baz"))

//big int
fmt.Printf("bigint = %s\n", libconfig.GetBigint(data, "bigint").String())

// float 64
fmt.Printf("float = %v\n", libconfig.GetFloat64(data, "float"))

// bool
fmt.Printf("bool = %v\n", libconfig.GetBool(data, "bool"))
group
data := []byte(`foo={bar= 1234; baz=0;};`)

// handy parse
fmt.Printf("foo.bar = %s\n", libconfig.GetString(data, "foo", "bar"))

//object parse
var (
    p libconfig.Parser
    v *libconfig.Value    
)
v, err := p.ParseBytes(data)
if err != nil {
    log.Fatal(err)
}

// use get with multiple parameters and check error
item, err := v.Get("foo", "bar").StringBytes()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("foo.bar = %s\n", string(item))

// use get with call chaining
fmt.Printf("foo.bar = %s\n", string(v.Get("foo").Get("bar").GetStringBytes()))

// use get array object
foo := v.GetObject("foo")
bar := foo.Get("bar")
fmt.Printf("my_array[0] = %s\n", bar.String())
array
data := []byte(`my_array = ["CT","CA","TX","NV","FL"];`)

// handy parse
fmt.Printf("my_array[0] = %s\n", libconfig.GetString(data, "my_array", "0"))

// object parse
var (
    p libconfig.Parser
    v *libconfig.Value
)

v, err := p.ParseBytes(data)
if err != nil {
      log.Fatal(err)
}

// use get with multiple parameters and check error
item, err := v.Get("my_array", "0").StringBytes()
if err != nil {
      log.Fatal(err)
}
fmt.Printf("my_array[0] = %s\n", string(item))

// use get with call chaining
fmt.Printf("my_array[0] = %s\n", v.Get("my_array").Get("0").String())

// use get array object
my_array := v.GetArray("my_array")
fmt.Printf("my_array[0] = %s\n", my_array[0].String())
list
data := []byte(`list = ( ( "abc", 123, true ), 1.234, ( /* an empty list */) );`)

// handy parse
fmt.Printf("list[0][0] = %s\n", libconfig.GetString(data, "list", "0", "0"))

// object parse
var (
    p libconfig.Parser
    v *libconfig.Value
)

v, err := p.ParseBytes(data)
if err != nil {
    log.Fatal(err)
}

// use get with multiple parameters and check error
item, err := v.Get("list", "0", "0").StringBytes()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("list[0][0] = %s\n", string(item))

// use get with call chaining
fmt.Printf("list[0][0] = %s\n", v.Get("list").Get("0").Get("0").String())

// use get array object
list := v.GetArray("list")
first_array := list[0].GetArray()
fmt.Printf("list[0][0] = %s\n", first_array[0].String())
mix
data := []byte(`foo=([{bar=1234; baz=0;}],)`)

// handy parse
fmt.Printf("foo[0][0].bar = %d\n", libconfig.GetInt(data, "foo", "0", "0", "bar"))

// object parse
var (
    p libconfig.Parser
    v *libconfig.Value
)

v, err := p.ParseBytes(data)
if err != nil {
    log.Fatal(err)
}

// use get with multiple parameters and check error
item, err := v.Get("foo", "0", "0", "bar").Int()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("foo[0][0].bar = %d\n", item)

// use get with call chaining
fmt.Printf("foo[0][0].bar = %d\n", v.Get("foo").Get("0").Get("0").GetInt("bar"))

// use get list object
foo := v.GetArray("foo")
first_list := foo[0].GetArray()
fmt.Printf("foo[0][0].bar = %s\n", first_list[0].GetObject().Get("bar"))
include
var p libconfig.Parser

// testdata/example4.cfg
v, err := p.ParseFile("testdata/example4.cfg")
if err != nil {
    log.Fatal(err)
}

// @include "cfg_includes/book*.cfg"
fmt.Printf("books[0].title=%s\n", v.GetArray("books")[0].GetStringBytes("title"))
fmt.Printf("books[0].title=%s\n", v.Get("books", "0").GetStringBytes("title"))
fmt.Printf("books[0].title=%s\n", v.Get("books").Get("0").GetStringBytes("title"))
fmt.Printf("books[0].author=%s\n", v.GetArray("books")[2].GetStringBytes("author"))

//@include "cfg_includes/cfg_subincludes/*.cfg"	
fmt.Printf("books[0].extra1=%s\n", v.GetArray("books")[0].GetStringBytes("extra1"))
fmt.Printf("books[3].extra1=%s\n", v.GetArray("books")[3].GetStringBytes("extra1"))
fmt.Printf("books[3].extra2=%d\n", v.GetArray("books")[3].GetInt("extra2"))
fmt.Printf("books[3].extra2=%d\n", v.GetInt("books", "3", "extra2"))
a complex demo
package main
import (
    "fmt"
    "log"
    "io/ioutil"
    "github.com/gitteamer/libconfig"
)
func main(){
    data, err := ioutil.ReadFile("testdata/demo.cfg")
    if err != nil {
        log.Fatal("read config file error: ", err.Error())
    }
    
    fmt.Printf("version = %s\n", libconfig.GetString(data, "version"))
    fmt.Printf("application.window.title = %s\n", libconfig.GetString(data, "application", "window", "title"))
    fmt.Printf("application.window.size.w = %d\n",  libconfig.GetInt(data, "application", "window", "size", "w"))
    fmt.Printf("application.window.size.h = %d\n", libconfig.GetInt(data, "application", "window", "size", "h"))
    fmt.Printf("application.window.pos.x = %d\n", libconfig.GetInt(data, "application", "window", "pos", "x"))
    fmt.Printf("application.window.pos.y = %d\n", libconfig.GetInt(data, "application", "window", "pos", "y"))
    
    fmt.Printf("application.list[0][0] = %s\n", libconfig.GetString(data, "application", "list", "0", "0"))
    fmt.Printf("application.list[0][1] = %d\n",  libconfig.GetInt(data, "application", "list", "0", "1"))
    fmt.Printf("application.list[0][2] = %t\n", libconfig.GetBool(data, "application", "list", "0", "2"))
    fmt.Printf("application.list[1] = %f\n",  libconfig.GetFloat64(data, "application", "list", "1"))
    fmt.Printf("application.list[2][0] =%s\n", libconfig.GetString(data, "application", "list", "2", "0"))
    
    fmt.Printf("application.books[0].title = %s\n", libconfig.GetString(data, "application", "books", "0", "title"))
    fmt.Printf("application.books[0].author = %s\n", libconfig.GetString(data, "application", "books", "0", "author"))
    fmt.Printf("application.books[0].price = %f\n", libconfig.GetFloat64(data, "application", "books", "0", "price"))
    fmt.Printf("application.books[0].qty = %d\n", libconfig.GetInt(data, "application", "books", "0", "qty"))
    fmt.Printf("application.books[1].title = %s\n", libconfig.GetString(data, "application", "books", "1", "title"))
    fmt.Printf("application.books[1].author = %s\n", libconfig.GetString(data, "application", "books", "1", "author"))
    fmt.Printf("application.books[1].price = %f\n", libconfig.GetFloat64(data, "application", "books", "1", "price"))
    fmt.Printf("application.books[1].qty = %d\n",  libconfig.GetInt(data, "application", "books", "1", "qty"))
    
    fmt.Printf("application.misc.pi = %.9f\n",  libconfig.GetFloat64(data, "application", "misc", "pi"))
    fmt.Printf("application.misc.bigint = %s\n", libconfig.GetBigint(data, "application", "misc", "bigint").String())
    fmt.Printf("application.misc.columns[0] = %s\n", libconfig.GetString(data, "application", "misc", "columns", "0"))
    fmt.Printf("application.misc.columns[1] = %s\n", libconfig.GetString(data, "application", "misc", "columns", "1"))
    fmt.Printf("application.misc.columns[2] = %s\n",  libconfig.GetString(data, "application", "misc", "columns", "2"))
    fmt.Printf("application.misc.bitmask = %d\n", libconfig.GetInt(data, "application", "misc", "bitmask"))
    fmt.Printf("application.misc.bitmask_hex = %s\n", libconfig.GetHex(data, "application", "misc", "bitmask"))
    
    // Output:
    // version = 1.0
    // application.window.title = My Application
    // application.window.size.w = 640
    // application.window.size.h = 480
    // application.window.pos.x = 350
    // application.window.pos.y = 250
    // application.list[0][0] = abc
    // application.list[0][1] = 123
    // application.list[0][2] = true
    // application.list[1] = 1.234000
    // application.list[2][0] =
    // application.books[0].title = Treasure Island
    // application.books[0].author = Robert Louis Stevenson
    // application.books[0].price = 29.950000
    // application.books[0].qty = 5
    // application.books[1].title = Snow Crash
    // application.books[1].author = Neal Stephenson
    // application.books[1].price = 9.990000
    // application.books[1].qty = 8
    // application.misc.pi = 3.141592654
    // application.misc.bigint = 9223372036854775807
    // application.misc.columns[0] = Last Name
    // application.misc.columns[1] = First Name
    // application.misc.columns[2] = MI
    // application.misc.bitmask = 8131
    // application.misc.bitmask_hex = 0x1FC3
}

Documentation

Overview

* The MIT License (MIT) * * Copyright (c) 2018 Aliaksandr Valialkin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Author: Aliaksandr Valialkin <valyala@gmail.com>

* The MIT License (MIT) * * Copyright (c) 2018 Aliaksandr Valialkin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Author: Aliaksandr Valialkin <valyala@gmail.com>

* The MIT License (MIT) * * Copyright (c) 2018 Aliaksandr Valialkin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Author: Aliaksandr Valialkin <valyala@gmail.com>

* The MIT License (MIT) * * Copyright (c) 2018 Aliaksandr Valialkin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Author: Aliaksandr Valialkin <valyala@gmail.com>

* The MIT License (MIT) * * Copyright (c) 2018 Aliaksandr Valialkin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Author: Aliaksandr Valialkin <valyala@gmail.com>

* The MIT License (MIT) * * Copyright (c) 2018 Aliaksandr Valialkin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Author: Aliaksandr Valialkin <valyala@gmail.com>

* The MIT License (MIT) * * Copyright (c) 2018 Aliaksandr Valialkin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Author: Aliaksandr Valialkin <valyala@gmail.com>

* The MIT License (MIT) * * Copyright (c) 2018 Aliaksandr Valialkin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Author: Aliaksandr Valialkin <valyala@gmail.com>

Index

Examples

Constants

View Source
const MaxDepth = 300

MaxDepth is the maximum depth for nested JSON.

Variables

This section is empty.

Functions

func Exists

func Exists(data []byte, keys ...string) bool

Exists returns true if the field identified by keys path exists in JSON data.

Array indexes may be represented as decimal numbers in keys.

False is returned on error. Use Parser for proper error handling.

Parser is faster when multiple fields must be checked in the JSON.

func GetBigint

func GetBigint(data []byte, keys ...string) *big.Int

func GetBool

func GetBool(data []byte, keys ...string) bool

GetBool returns boolean value for the field identified by keys path in JSON data.

Array indexes may be represented as decimal numbers in keys.

False is returned on error. Use Parser for proper error handling.

Parser is faster for obtaining multiple fields from JSON.

func GetBytes

func GetBytes(data []byte, keys ...string) []byte

GetBytes returns string value for the field identified by keys path in JSON data.

Array indexes may be represented as decimal numbers in keys.

nil is returned on error. Use Parser for proper error handling.

Parser is faster for obtaining multiple fields from JSON.

func GetFloat64

func GetFloat64(data []byte, keys ...string) float64

GetFloat64 returns float64 value for the field identified by keys path in JSON data.

Array indexes may be represented as decimal numbers in keys.

0 is returned on error. Use Parser for proper error handling.

Parser is faster for obtaining multiple fields from JSON.

func GetHex

func GetHex(data []byte, keys ...string) string

func GetInt

func GetInt(data []byte, keys ...string) int

GetInt returns int value for the field identified by keys path in JSON data.

Array indexes may be represented as decimal numbers in keys.

0 is returned on error. Use Parser for proper error handling.

Parser is faster for obtaining multiple fields from JSON.

func GetString

func GetString(data []byte, keys ...string) string

GetString returns string value for the field identified by keys path in JSON data.

Array indexes may be represented as decimal numbers in keys.

An empty string is returned on error. Use Parser for proper error handling.

Parser is faster for obtaining multiple fields from JSON.

func Validate

func Validate(s string) error

Validate validates JSON s.

func ValidateBytes

func ValidateBytes(b []byte) error

ValidateBytes validates JSON b.

Types

type Arena

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

Arena may be used for fast creation and re-use of Values.

Typical Arena lifecycle:

1) Construct Values via the Arena and Value.Set* calls.
2) Marshal the constructed Values with Value.MarshalTo call.
3) Reset all the constructed Values at once by Arena.Reset call.
4) Go to 1 and re-use the Arena.

It is unsafe calling Arena methods from concurrent goroutines. Use per-goroutine Arenas or ArenaPool instead.

func (*Arena) NewArray

func (a *Arena) NewArray() *Value

NewArray returns new empty array value.

New entries may be added to the returned array via Set* calls.

The returned array is valid until Reset is called on a.

func (*Arena) NewFalse

func (a *Arena) NewFalse() *Value

NewFalse return false value.

func (*Arena) NewNull

func (a *Arena) NewNull() *Value

NewNull returns null value.

func (*Arena) NewNumberFloat64

func (a *Arena) NewNumberFloat64(f float64) *Value

NewNumberFloat64 returns new number value containing f.

The returned number is valid until Reset is called on a.

func (*Arena) NewNumberInt

func (a *Arena) NewNumberInt(n int) *Value

NewNumberInt returns new number value containing n.

The returned number is valid until Reset is called on a.

func (*Arena) NewNumberString

func (a *Arena) NewNumberString(s string) *Value

NewNumberString returns new number value containing s.

The returned number is valid until Reset is called on a.

func (*Arena) NewObject

func (a *Arena) NewObject() *Value

NewObject returns new empty object value.

New entries may be added to the returned object via Set call.

The returned object is valid until Reset is called on a.

func (*Arena) NewString

func (a *Arena) NewString(s string) *Value

NewString returns new string value containing s.

The returned string is valid until Reset is called on a.

func (*Arena) NewStringBytes

func (a *Arena) NewStringBytes(b []byte) *Value

NewStringBytes returns new string value containing b.

The returned string is valid until Reset is called on a.

func (*Arena) NewTrue

func (a *Arena) NewTrue() *Value

NewTrue returns true value.

func (*Arena) Reset

func (a *Arena) Reset()

Reset resets all the Values allocated by a.

Values previously allocated by a cannot be used after the Reset call.

type ArenaPool

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

ArenaPool may be used for pooling Arenas for similarly typed JSONs.

func (*ArenaPool) Get

func (ap *ArenaPool) Get() *Arena

Get returns an Arena from ap.

The Arena must be Put to ap after use.

func (*ArenaPool) Put

func (ap *ArenaPool) Put(a *Arena)

Put returns a to ap.

a and objects created by a cannot be used after a is put into ap.

type Object

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

Object represents JSON object.

Object cannot be used from concurrent goroutines. Use per-goroutine parsers or ParserPool instead.

func (*Object) Del

func (o *Object) Del(key string)

Del deletes the entry with the given key from o.

Example
package main

import (
	"fastjson"
	"fmt"
	"log"
)

func main() {
	v := fastjson.MustParse(`{"foo": 123, "bar": [1,2], "baz": "xyz"}`)
	o, err := v.Object()
	if err != nil {
		log.Fatalf("cannot otain object: %s", err)
	}
	fmt.Printf("%s\n", o)

	o.Del("bar")
	fmt.Printf("%s\n", o)

	o.Del("foo")
	fmt.Printf("%s\n", o)

	o.Del("baz")
	fmt.Printf("%s\n", o)

}
Output:

{"foo":123,"bar":[1,2],"baz":"xyz"}
{"foo":123,"baz":"xyz"}
{"baz":"xyz"}
{}

func (*Object) Get

func (o *Object) Get(key string) *Value

Get returns the value for the given key in the o.

Returns nil if the value for the given key isn't found.

The returned value is valid until Parse is called on the Parser returned o.

func (*Object) Len

func (o *Object) Len() int

Len returns the number of items in the o.

func (*Object) MarshalTo

func (o *Object) MarshalTo(dst []byte) []byte

MarshalTo appends marshaled o to dst and returns the result.

func (*Object) Set

func (o *Object) Set(key string, value *Value)

Set sets (key, value) entry in the o.

The value must be unchanged during o lifetime.

func (*Object) String

func (o *Object) String() string

String returns string representation for the o.

This function is for debugging purposes only. It isn't optimized for speed. See MarshalTo instead.

func (*Object) Visit

func (o *Object) Visit(f func(key []byte, v *Value))

Visit calls f for each item in the o in the original order of the parsed JSON.

f cannot hold key and/or v after returning.

Example
package main

import (
	"fastjson"
	"fmt"
	"log"
)

func main() {
	s := `{
		"obj": { "foo": 1234 },
		"arr": [ 23,4, "bar" ],
		"str": "foobar"
	}`

	var p fastjson.Parser
	v, err := p.Parse(s)
	if err != nil {
		log.Fatalf("cannot parse json: %s", err)
	}
	o, err := v.Object()
	if err != nil {
		log.Fatalf("cannot obtain object from json value: %s", err)
	}

	o.Visit(func(k []byte, v *fastjson.Value) {
		switch string(k) {
		case "obj":
			fmt.Printf("object %s\n", v)
		case "arr":
			fmt.Printf("array %s\n", v)
		case "str":
			fmt.Printf("string %s\n", v)
		}
	})

}
Output:

object {"foo":1234}
array [23,4,"bar"]
string "foobar"

type Parser

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

Parser parses JSON.

Parser may be re-used for subsequent parsing.

Parser cannot be used from concurrent goroutines. Use per-goroutine parsers or ParserPool instead.

func (*Parser) Parse

func (p *Parser) Parse(s string) (*Value, error)

Parse parses s containing JSON.

The returned value is valid until the next call to Parse*.

Use Scanner if a stream of JSON values must be parsed.

Example
package main

import (
	"fastjson"
	"fmt"
	"log"
)

func main() {
	var p fastjson.Parser
	v, err := p.Parse(`{"foo":"bar", "baz": 123}`)
	if err != nil {
		log.Fatalf("cannot parse json: %s", err)
	}

	fmt.Printf("foo=%s, baz=%d", v.GetStringBytes("foo"), v.GetInt("baz"))

}
Output:

foo=bar, baz=123
Example (Reuse)
package main

import (
	"fastjson"
	"fmt"
	"log"
	"strconv"
)

func main() {
	var p fastjson.Parser

	// p may be re-used for parsing multiple json strings.
	// This improves parsing speed by reducing the number
	// of memory allocations.
	//
	// Parse call invalidates all the objects previously obtained from p,
	// so don't hold these objects after parsing the next json.

	for i := 0; i < 3; i++ {
		s := fmt.Sprintf(`["foo_%d","bar_%d","%d"]`, i, i, i)
		v, err := p.Parse(s)
		if err != nil {
			log.Fatalf("cannot parse json: %s", err)
		}
		key := strconv.Itoa(i)
		fmt.Printf("a[%d]=%s\n", i, v.GetStringBytes(key))
	}

}
Output:

a[0]=foo_0
a[1]=bar_1
a[2]=2

func (*Parser) ParseBytes

func (p *Parser) ParseBytes(b []byte) (*Value, error)

ParseBytes parses b containing JSON.

The returned Value is valid until the next call to Parse*.

Use Scanner if a stream of JSON values must be parsed.

func (*Parser) ParseFile added in v1.0.0

func (p *Parser) ParseFile(path string) (*Value, error)

ParseFile for parse a file

for @include scene, use ParseFile

path is config file path

type ParserPool

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

ParserPool may be used for pooling Parsers for similarly typed JSONs.

func (*ParserPool) Get

func (pp *ParserPool) Get() *Parser

Get returns a Parser from pp.

The Parser must be Put to pp after use.

func (*ParserPool) Put

func (pp *ParserPool) Put(p *Parser)

Put returns p to pp.

p and objects recursively returned from p cannot be used after p is put into pp.

type Scanner

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

Scanner scans a series of JSON values. Values may be delimited by whitespace.

Scanner may parse JSON lines ( http://jsonlines.org/ ).

Scanner may be re-used for subsequent parsing.

Scanner cannot be used from concurrent goroutines.

Use Parser for parsing only a single JSON value.

Example
package main

import (
	"fastjson"
	"fmt"
	"log"
)

func main() {
	var sc fastjson.Scanner

	sc.Init(`   {"foo":  "bar"  }[  ]
		12345"xyz" true false null    `)

	for sc.Next() {
		fmt.Printf("%s\n", sc.Value())
	}
	if err := sc.Error(); err != nil {
		log.Fatalf("unexpected error: %s", err)
	}

}
Output:

{"foo":"bar"}
[]
12345
"xyz"
true
false
null
Example (Reuse)
package main

import (
	"fastjson"
	"fmt"
	"log"
)

func main() {
	var sc fastjson.Scanner

	// The sc may be re-used in order to reduce the number
	// of memory allocations.
	for i := 0; i < 3; i++ {
		s := fmt.Sprintf(`[%d] "%d"`, i, i)
		sc.Init(s)
		for sc.Next() {
			fmt.Printf("%s,", sc.Value())
		}
		if err := sc.Error(); err != nil {
			log.Fatalf("unexpected error: %s", err)
		}
		fmt.Printf("\n")
	}

}
Output:

[0],"0",
[1],"1",
[2],"2",

func (*Scanner) Error

func (sc *Scanner) Error() error

Error returns the last error.

func (*Scanner) Init

func (sc *Scanner) Init(s string)

Init initializes sc with the given s.

s may contain multiple JSON values, which may be delimited by whitespace.

func (*Scanner) InitBytes

func (sc *Scanner) InitBytes(b []byte)

InitBytes initializes sc with the given b.

b may contain multiple JSON values, which may be delimited by whitespace.

func (*Scanner) Next

func (sc *Scanner) Next() bool

Next parses the next JSON value from s passed to Init.

Returns true on success. The parsed value is available via Value call.

Returns false either on error or on the end of s. Call Error in order to determine the cause of the returned false.

func (*Scanner) Value

func (sc *Scanner) Value() *Value

Value returns the last parsed value.

The value is valid until the Next call.

type Type

type Type int

Type represents JSON type.

const (
	// TypeNull is JSON null.
	TypeNull Type = 0

	// TypeObject is JSON object type.
	TypeObject Type = 1

	// TypeArray is JSON array type.
	TypeArray Type = 2

	// TypeString is JSON string type.
	TypeString Type = 3

	// TypeNumber is JSON number type.
	TypeNumber Type = 4

	// TypeTrue is JSON true.
	TypeTrue Type = 5

	// TypeFalse is JSON false.
	TypeFalse Type = 6
)

func (Type) String

func (t Type) String() string

String returns string representation of t.

type Value

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

Value represents any JSON value.

Call Type in order to determine the actual type of the JSON value.

Value cannot be used from concurrent goroutines. Use per-goroutine parsers or ParserPool instead.

func MustParse

func MustParse(s string) *Value

MustParse parses json string s.

The function panics if s cannot be parsed. The function is slower than the Parser.Parse for re-used Parser.

func MustParseBytes

func MustParseBytes(b []byte) *Value

MustParseBytes parses b containing json.

The function panics if b cannot be parsed. The function is slower than the Parser.ParseBytes for re-used Parser.

func Parse

func Parse(s string) (*Value, error)

Parse parses json string s.

The function is slower than the Parser.Parse for re-used Parser.

func ParseBytes

func ParseBytes(b []byte) (*Value, error)

ParseBytes parses b containing json.

The function is slower than the Parser.ParseBytes for re-used Parser.

Example

parse bytes demo.cfg

package main

import (
	"fmt"
	"io/ioutil"
	"log"

	"github.com/gitteamer/libconfig"
)

func main() {
	data, err := ioutil.ReadFile("testdata/demo.cfg")
	if err != nil {
		log.Fatal("read config file error: ", err.Error())
	}

	fmt.Printf("version = %s\n", libconfig.GetString(data, "version"))
	fmt.Printf("application.window.title = %s\n", libconfig.GetString(data, "application", "window", "title"))
	fmt.Printf("application.window.size.w = %d\n", libconfig.GetInt(data, "application", "window", "size", "w"))
	fmt.Printf("application.window.size.h = %d\n", libconfig.GetInt(data, "application", "window", "size", "h"))
	fmt.Printf("application.window.pos.x = %d\n", libconfig.GetInt(data, "application", "window", "pos", "x"))
	fmt.Printf("application.window.pos.y = %d\n", libconfig.GetInt(data, "application", "window", "pos", "y"))

	fmt.Printf("application.list[0][0] = %s\n", libconfig.GetString(data, "application", "list", "0", "0"))
	fmt.Printf("application.list[0][1] = %d\n", libconfig.GetInt(data, "application", "list", "0", "1"))
	fmt.Printf("application.list[0][2] = %t\n", libconfig.GetBool(data, "application", "list", "0", "2"))
	fmt.Printf("application.list[1] = %f\n", libconfig.GetFloat64(data, "application", "list", "1"))
	fmt.Printf("application.list[2][0] =%s\n", libconfig.GetString(data, "application", "list", "2", "0"))

	fmt.Printf("application.books[0].title = %s\n", libconfig.GetString(data, "application", "books", "0", "title"))
	fmt.Printf("application.books[0].author = %s\n", libconfig.GetString(data, "application", "books", "0", "author"))
	fmt.Printf("application.books[0].price = %f\n", libconfig.GetFloat64(data, "application", "books", "0", "price"))
	fmt.Printf("application.books[0].qty = %d\n", libconfig.GetInt(data, "application", "books", "0", "qty"))
	fmt.Printf("application.books[1].title = %s\n", libconfig.GetString(data, "application", "books", "1", "title"))
	fmt.Printf("application.books[1].author = %s\n", libconfig.GetString(data, "application", "books", "1", "author"))
	fmt.Printf("application.books[1].price = %f\n", libconfig.GetFloat64(data, "application", "books", "1", "price"))
	fmt.Printf("application.books[1].qty = %d\n", libconfig.GetInt(data, "application", "books", "1", "qty"))

	fmt.Printf("application.misc.pi = %.9f\n", libconfig.GetFloat64(data, "application", "misc", "pi"))
	fmt.Printf("application.misc.bigint = %s\n", libconfig.GetBigint(data, "application", "misc", "bigint").String())
	fmt.Printf("application.misc.columns[0] = %s\n", libconfig.GetString(data, "application", "misc", "columns", "0"))
	fmt.Printf("application.misc.columns[1] = %s\n", libconfig.GetString(data, "application", "misc", "columns", "1"))
	fmt.Printf("application.misc.columns[2] = %s\n", libconfig.GetString(data, "application", "misc", "columns", "2"))
	fmt.Printf("application.misc.bitmask = %d\n", libconfig.GetInt(data, "application", "misc", "bitmask"))
	fmt.Printf("application.misc.bitmask_hex = %s\n", libconfig.GetHex(data, "application", "misc", "bitmask"))

}
Output:

version = 1.0
application.window.title = My Application
application.window.size.w = 640
application.window.size.h = 480
application.window.pos.x = 350
application.window.pos.y = 250
application.list[0][0] = abc
application.list[0][1] = 123
application.list[0][2] = true
application.list[1] = 1.234000
application.list[2][0] =
application.books[0].title = Treasure Island
application.books[0].author = Robert Louis Stevenson
application.books[0].price = 29.950000
application.books[0].qty = 5
application.books[1].title = Snow Crash
application.books[1].author = Neal Stephenson
application.books[1].price = 9.990000
application.books[1].qty = 8
application.misc.pi = 3.141592654
application.misc.bigint = 9223372036854775807
application.misc.columns[0] = Last Name
application.misc.columns[1] = First Name
application.misc.columns[2] = MI
application.misc.bitmask = 8131
application.misc.bitmask_hex = 0x1FC3

func (*Value) Array

func (v *Value) Array() ([]*Value, error)

Array returns the underlying JSON array for the v.

The returned array is valid until Parse is called on the Parser returned v.

Use GetArray if you don't need error handling.

func (*Value) Bool

func (v *Value) Bool() (bool, error)

Bool returns the underlying JSON bool for the v.

Use GetBool if you don't need error handling.

func (*Value) Del

func (v *Value) Del(key string)

Del deletes the entry with the given key from array or object v.

Example
package main

import (
	"fastjson"
	"fmt"
)

func main() {
	v := fastjson.MustParse(`{"foo": 123, "bar": [1,2], "baz": "xyz"}`)
	fmt.Printf("%s\n", v)

	v.Del("foo")
	fmt.Printf("%s\n", v)

	v.Get("bar").Del("0")
	fmt.Printf("%s\n", v)

}
Output:

{"foo":123,"bar":[1,2],"baz":"xyz"}
{"bar":[1,2],"baz":"xyz"}
{"bar":[2],"baz":"xyz"}

func (*Value) Exists

func (v *Value) Exists(keys ...string) bool

Exists returns true if the field exists for the given keys path.

Array indexes may be represented as decimal numbers in keys.

func (*Value) Float64

func (v *Value) Float64() (float64, error)

Float64 returns the underlying JSON number for the v.

Use GetFloat64 if you don't need error handling.

func (*Value) Get

func (v *Value) Get(keys ...string) *Value

Get returns value by the given keys path.

Array indexes may be represented as decimal numbers in keys.

nil is returned for non-existing keys path.

The returned value is valid until Parse is called on the Parser returned v.

Example
package main

import (
	"fastjson"
	"fmt"
	"log"
)

func main() {
	s := `{"foo":[{"bar":{"baz":123,"x":"434"},"y":[]},[null, false]],"qwe":true}`
	var p fastjson.Parser
	v, err := p.Parse(s)
	if err != nil {
		log.Fatalf("cannot parse json: %s", err)
	}

	vv := v.Get("foo", "0", "bar", "x")
	fmt.Printf("foo[0].bar.x=%s\n", vv.GetStringBytes())

	vv = v.Get("qwe")
	fmt.Printf("qwe=%v\n", vv.GetBool())

	vv = v.Get("foo", "1")
	fmt.Printf("foo[1]=%s\n", vv)

	vv = v.Get("foo").Get("1").Get("1")
	fmt.Printf("foo[1][1]=%s\n", vv)

	// non-existing key
	vv = v.Get("foo").Get("bar").Get("baz", "1234")
	fmt.Printf("foo.bar.baz[1234]=%v\n", vv)

}
Output:

foo[0].bar.x=434
qwe=true
foo[1]=[null,false]
foo[1][1]=false
foo.bar.baz[1234]=<nil>

func (*Value) GetArray

func (v *Value) GetArray(keys ...string) []*Value

GetArray returns array value by the given keys path.

Array indexes may be represented as decimal numbers in keys.

nil is returned for non-existing keys path or for invalid value type.

The returned array is valid until Parse is called on the Parser returned v.

func (*Value) GetBigint

func (v *Value) GetBigint(keys ...string) *big.Int

func (*Value) GetBool

func (v *Value) GetBool(keys ...string) bool

GetBool returns bool value by the given keys path.

Array indexes may be represented as decimal numbers in keys.

false is returned for non-existing keys path or for invalid value type.

func (*Value) GetFloat64

func (v *Value) GetFloat64(keys ...string) float64

GetFloat64 returns float64 value by the given keys path.

Array indexes may be represented as decimal numbers in keys.

0 is returned for non-existing keys path or for invalid value type.

func (*Value) GetHex

func (v *Value) GetHex(keys ...string) string

func (*Value) GetInt

func (v *Value) GetInt(keys ...string) int

GetInt returns int value by the given keys path.

Array indexes may be represented as decimal numbers in keys.

0 is returned for non-existing keys path or for invalid value type.

func (*Value) GetInt64

func (v *Value) GetInt64(keys ...string) int64

GetInt64 returns int64 value by the given keys path.

Array indexes may be represented as decimal numbers in keys.

0 is returned for non-existing keys path or for invalid value type.

func (*Value) GetObject

func (v *Value) GetObject(keys ...string) *Object

GetObject returns object value by the given keys path.

Array indexes may be represented as decimal numbers in keys.

nil is returned for non-existing keys path or for invalid value type.

The returned object is valid until Parse is called on the Parser returned v.

func (*Value) GetRawBytes

func (v *Value) GetRawBytes(keys ...string) []byte

func (*Value) GetStringBytes

func (v *Value) GetStringBytes(keys ...string) []byte

GetStringBytes returns string value by the given keys path.

Array indexes may be represented as decimal numbers in keys.

nil is returned for non-existing keys path or for invalid value type.

The returned string is valid until Parse is called on the Parser returned v.

Example
package main

import (
	"fastjson"
	"fmt"
	"log"
)

func main() {
	s := `[
		{"foo": "bar"},
		[123, "baz"]
	]`

	var p fastjson.Parser
	v, err := p.Parse(s)
	if err != nil {
		log.Fatalf("cannot parse json: %s", err)
	}
	fmt.Printf("v[0].foo = %q\n", v.GetStringBytes("0", "foo"))
	fmt.Printf("v[1][1] = %q\n", v.GetStringBytes("1", "1"))
	fmt.Printf("v[1][0] = %q\n", v.GetStringBytes("1", "0"))
	fmt.Printf("v.foo.bar.baz = %q\n", v.GetStringBytes("foo", "bar", "baz"))

}
Output:

v[0].foo = "bar"
v[1][1] = "baz"
v[1][0] = ""
v.foo.bar.baz = ""

func (*Value) GetUint

func (v *Value) GetUint(keys ...string) uint

GetUint returns uint value by the given keys path.

Array indexes may be represented as decimal numbers in keys.

0 is returned for non-existing keys path or for invalid value type.

func (*Value) GetUint64

func (v *Value) GetUint64(keys ...string) uint64

GetUint64 returns uint64 value by the given keys path.

Array indexes may be represented as decimal numbers in keys.

0 is returned for non-existing keys path or for invalid value type.

func (*Value) Int

func (v *Value) Int() (int, error)

Int returns the underlying JSON int for the v.

Use GetInt if you don't need error handling.

func (*Value) Int64

func (v *Value) Int64() (int64, error)

Int64 returns the underlying JSON int64 for the v.

Use GetInt64 if you don't need error handling.

func (*Value) MarshalTo

func (v *Value) MarshalTo(dst []byte) []byte

MarshalTo appends marshaled v to dst and returns the result.

Example
package main

import (
	"fastjson"
	"fmt"
	"log"
)

func main() {
	s := `{
		"name": "John",
		"items": [
			{
				"key": "foo",
				"value": 123.456,
				"arr": [1, "foo"]
			},
			{
				"key": "bar",
				"field": [3, 4, 5]
			}
		]
	}`
	var p fastjson.Parser
	v, err := p.Parse(s)
	if err != nil {
		log.Fatalf("cannot parse json: %s", err)
	}

	// Marshal items.0 into newly allocated buffer.
	buf := v.Get("items", "0").MarshalTo(nil)
	fmt.Printf("items.0 = %s\n", buf)

	// Re-use buf for marshaling items.1.
	buf = v.Get("items", "1").MarshalTo(buf[:0])
	fmt.Printf("items.1 = %s\n", buf)

}
Output:

items.0 = {"key":"foo","value":123.456,"arr":[1,"foo"]}
items.1 = {"key":"bar","field":[3,4,5]}

func (*Value) Object

func (v *Value) Object() (*Object, error)

Object returns the underlying JSON object for the v.

The returned object is valid until Parse is called on the Parser returned v.

Use GetObject if you don't need error handling.

func (*Value) Set

func (v *Value) Set(key string, value *Value)

Set sets (key, value) entry in the array or object v.

The value must be unchanged during v lifetime.

Example
package main

import (
	"fastjson"
	"fmt"
)

func main() {
	v := fastjson.MustParse(`{"foo":1,"bar":[2,3]}`)

	// Replace `foo` value with "xyz"
	v.Set("foo", fastjson.MustParse(`"xyz"`))
	// Add "newv":123
	v.Set("newv", fastjson.MustParse(`123`))
	fmt.Printf("%s\n", v)

	// Replace `bar.1` with {"x":"y"}
	v.Get("bar").Set("1", fastjson.MustParse(`{"x":"y"}`))
	// Add `bar.3="qwe"
	v.Get("bar").Set("3", fastjson.MustParse(`"qwe"`))
	fmt.Printf("%s\n", v)

}
Output:

{"foo":"xyz","bar":[2,3],"newv":123}
{"foo":"xyz","bar":[2,{"x":"y"},null,"qwe"],"newv":123}

func (*Value) SetArrayItem

func (v *Value) SetArrayItem(idx int, value *Value)

SetArrayItem sets the value in the array v at idx position.

The value must be unchanged during v lifetime.

func (*Value) String

func (v *Value) String() string

String returns string representation of the v.

The function is for debugging purposes only. It isn't optimized for speed. See MarshalTo instead.

Don't confuse this function with StringBytes, which must be called for obtaining the underlying JSON string for the v.

func (*Value) StringBytes

func (v *Value) StringBytes() ([]byte, error)

StringBytes returns the underlying JSON string for the v.

The returned string is valid until Parse is called on the Parser returned v.

Use GetStringBytes if you don't need error handling.

func (*Value) Type

func (v *Value) Type() Type

Type returns the type of the v.

Example
package main

import (
	"fastjson"
	"fmt"
	"log"
)

func main() {
	s := `{
		"object": {},
		"array": [],
		"string": "foobar",
		"number": 123.456,
		"true": true,
		"false": false,
		"null": null
	}`

	var p fastjson.Parser
	v, err := p.Parse(s)
	if err != nil {
		log.Fatalf("cannot parse json: %s", err)
	}

	fmt.Printf("%s\n", v.Get("object").Type())
	fmt.Printf("%s\n", v.Get("array").Type())
	fmt.Printf("%s\n", v.Get("string").Type())
	fmt.Printf("%s\n", v.Get("number").Type())
	fmt.Printf("%s\n", v.Get("true").Type())
	fmt.Printf("%s\n", v.Get("false").Type())
	fmt.Printf("%s\n", v.Get("null").Type())

}
Output:

object
array
string
number
true
false
null

func (*Value) Uint

func (v *Value) Uint() (uint, error)

Uint returns the underlying JSON uint for the v.

Use GetInt if you don't need error handling.

func (*Value) Uint64

func (v *Value) Uint64() (uint64, error)

Uint64 returns the underlying JSON uint64 for the v.

Use GetInt64 if you don't need error handling.

Directories

Path Synopsis
* The MIT License (MIT) * * Copyright (c) 2018 Aliaksandr Valialkin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software.
* The MIT License (MIT) * * Copyright (c) 2018 Aliaksandr Valialkin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL