gitee.com/quant1x/gox@v1.7.6/fastjson/parser.go (about)

     1  package fastjson
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"strings"
     7  	"unicode/utf16"
     8  )
     9  
    10  // Parser parses JSON.
    11  //
    12  // Parser may be re-used for subsequent parsing.
    13  //
    14  // Parser cannot be used from concurrent goroutines.
    15  // Use per-goroutine parsers or ParserPool instead.
    16  type Parser struct {
    17  	// b contains working copy of the string to be parsed.
    18  	b []byte
    19  
    20  	// c is a cache for fastjson values.
    21  	c cache
    22  }
    23  
    24  // Parse parses s containing JSON.
    25  //
    26  // The returned value is valid until the next call to Parse*.
    27  //
    28  // Use Scanner if a stream of JSON values must be parsed.
    29  func (p *Parser) Parse(s string) (*Value, error) {
    30  	s = skipWS(s)
    31  	p.b = append(p.b[:0], s...)
    32  	p.c.reset()
    33  
    34  	v, tail, err := parseValue(b2s(p.b), &p.c)
    35  	if err != nil {
    36  		return nil, fmt.Errorf("cannot parse JSON: %s; unparsed tail: %q", err, startEndString(tail))
    37  	}
    38  	tail = skipWS(tail)
    39  	if len(tail) > 0 {
    40  		return nil, fmt.Errorf("unexpected tail: %q", startEndString(tail))
    41  	}
    42  	return v, nil
    43  }
    44  
    45  // ParseBytes parses b containing JSON.
    46  //
    47  // The returned Value is valid until the next call to Parse*.
    48  //
    49  // Use Scanner if a stream of JSON values must be parsed.
    50  func (p *Parser) ParseBytes(b []byte) (*Value, error) {
    51  	return p.Parse(b2s(b))
    52  }
    53  
    54  type cache struct {
    55  	vs []Value
    56  }
    57  
    58  func (c *cache) reset() {
    59  	c.vs = c.vs[:0]
    60  }
    61  
    62  func (c *cache) getValue() *Value {
    63  	if cap(c.vs) > len(c.vs) {
    64  		c.vs = c.vs[:len(c.vs)+1]
    65  	} else {
    66  		c.vs = append(c.vs, Value{})
    67  	}
    68  	// Do not reset the value, since the caller must properly init it.
    69  	return &c.vs[len(c.vs)-1]
    70  }
    71  
    72  func skipWS(s string) string {
    73  	if len(s) == 0 || s[0] > 0x20 {
    74  		// Fast path.
    75  		return s
    76  	}
    77  	return skipWSSlow(s)
    78  }
    79  
    80  func skipWSSlow(s string) string {
    81  	if len(s) == 0 || s[0] != 0x20 && s[0] != 0x0A && s[0] != 0x09 && s[0] != 0x0D {
    82  		return s
    83  	}
    84  	for i := 1; i < len(s); i++ {
    85  		if s[i] != 0x20 && s[i] != 0x0A && s[i] != 0x09 && s[i] != 0x0D {
    86  			return s[i:]
    87  		}
    88  	}
    89  	return ""
    90  }
    91  
    92  type kv struct {
    93  	k string
    94  	v *Value
    95  }
    96  
    97  func parseValue(s string, c *cache) (*Value, string, error) {
    98  	if len(s) == 0 {
    99  		return nil, s, fmt.Errorf("cannot parse empty string")
   100  	}
   101  
   102  	if s[0] == '{' {
   103  		v, tail, err := parseObject(s[1:], c)
   104  		if err != nil {
   105  			return nil, tail, fmt.Errorf("cannot parse object: %s", err)
   106  		}
   107  		return v, tail, nil
   108  	}
   109  	if s[0] == '[' {
   110  		v, tail, err := parseArray(s[1:], c)
   111  		if err != nil {
   112  			return nil, tail, fmt.Errorf("cannot parse array: %s", err)
   113  		}
   114  		return v, tail, nil
   115  	}
   116  	if s[0] == '"' {
   117  		ss, tail, err := parseRawString(s[1:])
   118  		if err != nil {
   119  			return nil, tail, fmt.Errorf("cannot parse string: %s", err)
   120  		}
   121  		v := c.getValue()
   122  		v.t = typeRawString
   123  		v.s = ss
   124  		return v, tail, nil
   125  	}
   126  	if s[0] == 't' {
   127  		if len(s) < len("true") || s[:len("true")] != "true" {
   128  			return nil, s, fmt.Errorf("unexpected value found: %q", s)
   129  		}
   130  		return valueTrue, s[len("true"):], nil
   131  	}
   132  	if s[0] == 'f' {
   133  		if len(s) < len("false") || s[:len("false")] != "false" {
   134  			return nil, s, fmt.Errorf("unexpected value found: %q", s)
   135  		}
   136  		return valueFalse, s[len("false"):], nil
   137  	}
   138  	if s[0] == 'n' {
   139  		if len(s) < len("null") || s[:len("null")] != "null" {
   140  			return nil, s, fmt.Errorf("unexpected value found: %q", s)
   141  		}
   142  		return valueNull, s[len("null"):], nil
   143  	}
   144  
   145  	ns, tail, err := parseRawNumber(s)
   146  	if err != nil {
   147  		return nil, tail, fmt.Errorf("cannot parse number: %s", err)
   148  	}
   149  	v := c.getValue()
   150  	v.t = TypeNumber
   151  	v.s = ns
   152  	return v, tail, nil
   153  }
   154  
   155  func parseArray(s string, c *cache) (*Value, string, error) {
   156  	s = skipWS(s)
   157  	if len(s) == 0 {
   158  		return nil, s, fmt.Errorf("missing ']'")
   159  	}
   160  
   161  	if s[0] == ']' {
   162  		v := c.getValue()
   163  		v.t = TypeArray
   164  		v.a = v.a[:0]
   165  		return v, s[1:], nil
   166  	}
   167  
   168  	a := c.getValue()
   169  	a.t = TypeArray
   170  	a.a = a.a[:0]
   171  	for {
   172  		var v *Value
   173  		var err error
   174  
   175  		s = skipWS(s)
   176  		v, s, err = parseValue(s, c)
   177  		if err != nil {
   178  			return nil, s, fmt.Errorf("cannot parse array value: %s", err)
   179  		}
   180  		a.a = append(a.a, v)
   181  
   182  		s = skipWS(s)
   183  		if len(s) == 0 {
   184  			return nil, s, fmt.Errorf("unexpected end of array")
   185  		}
   186  		if s[0] == ',' {
   187  			s = s[1:]
   188  			continue
   189  		}
   190  		if s[0] == ']' {
   191  			s = s[1:]
   192  			return a, s, nil
   193  		}
   194  		return nil, s, fmt.Errorf("missing ',' after array value")
   195  	}
   196  }
   197  
   198  func parseObject(s string, c *cache) (*Value, string, error) {
   199  	s = skipWS(s)
   200  	if len(s) == 0 {
   201  		return nil, s, fmt.Errorf("missing '}'")
   202  	}
   203  
   204  	if s[0] == '}' {
   205  		v := c.getValue()
   206  		v.t = TypeObject
   207  		v.o.reset()
   208  		return v, s[1:], nil
   209  	}
   210  
   211  	o := c.getValue()
   212  	o.t = TypeObject
   213  	o.o.reset()
   214  	for {
   215  		var err error
   216  		kv := o.o.getKV()
   217  
   218  		// Parse key.
   219  		s = skipWS(s)
   220  		if len(s) == 0 {
   221  			return nil, s, fmt.Errorf(`cannot find object key`)
   222  		}
   223  		unquotedKey := false
   224  		pos_start := 1
   225  		if s[0] != '"' && s[0] != '\'' {
   226  			unquotedKey = true
   227  			pos_start = 0
   228  		}
   229  		kv.k, s, err = parseRawKey(s[pos_start:], unquotedKey)
   230  		if err != nil {
   231  			return nil, s, fmt.Errorf("cannot parse object key: %s", err)
   232  		}
   233  		s = skipWS(s)
   234  		if len(s) == 0 || s[0] != ':' {
   235  			return nil, s, fmt.Errorf("missing ':' after object key")
   236  		}
   237  		s = s[1:]
   238  
   239  		// Parse value
   240  		s = skipWS(s)
   241  		kv.v, s, err = parseValue(s, c)
   242  		if err != nil {
   243  			return nil, s, fmt.Errorf("cannot parse object value: %s", err)
   244  		}
   245  		s = skipWS(s)
   246  		if len(s) == 0 {
   247  			return nil, s, fmt.Errorf("unexpected end of object")
   248  		}
   249  		if s[0] == ',' {
   250  			s = s[1:]
   251  			continue
   252  		}
   253  		if s[0] == '}' {
   254  			return o, s[1:], nil
   255  		}
   256  		return nil, s, fmt.Errorf("missing ',' after object value")
   257  	}
   258  }
   259  
   260  func escapeString(dst []byte, s string) []byte {
   261  	if !hasSpecialChars(s) {
   262  		// Fast path - nothing to escape.
   263  		dst = append(dst, '"')
   264  		dst = append(dst, s...)
   265  		dst = append(dst, '"')
   266  		return dst
   267  	}
   268  
   269  	// Slow path.
   270  	return strconv.AppendQuote(dst, s)
   271  }
   272  
   273  func hasSpecialChars(s string) bool {
   274  	if strings.IndexByte(s, '"') >= 0 || strings.IndexByte(s, '\\') >= 0 {
   275  		return true
   276  	}
   277  	for i := 0; i < len(s); i++ {
   278  		if s[i] < 0x20 {
   279  			return true
   280  		}
   281  	}
   282  	return false
   283  }
   284  
   285  func unescapeStringBestEffort(s string) string {
   286  	n := strings.IndexByte(s, '\\')
   287  	if n < 0 {
   288  		// Fast path - nothing to unescape.
   289  		return s
   290  	}
   291  
   292  	// Slow path - unescape string.
   293  	b := s2b(s) // It is safe to do, since s points to a byte slice in Parser.b.
   294  	b = b[:n]
   295  	s = s[n+1:]
   296  	for len(s) > 0 {
   297  		ch := s[0]
   298  		s = s[1:]
   299  		switch ch {
   300  		case '"':
   301  			b = append(b, '"')
   302  		case '\\':
   303  			b = append(b, '\\')
   304  		case '/':
   305  			b = append(b, '/')
   306  		case 'b':
   307  			b = append(b, '\b')
   308  		case 'f':
   309  			b = append(b, '\f')
   310  		case 'n':
   311  			b = append(b, '\n')
   312  		case 'r':
   313  			b = append(b, '\r')
   314  		case 't':
   315  			b = append(b, '\t')
   316  		case 'u':
   317  			if len(s) < 4 {
   318  				// Too short escape sequence. Just store it unchanged.
   319  				b = append(b, "\\u"...)
   320  				break
   321  			}
   322  			xs := s[:4]
   323  			x, err := strconv.ParseUint(xs, 16, 16)
   324  			if err != nil {
   325  				// Invalid escape sequence. Just store it unchanged.
   326  				b = append(b, "\\u"...)
   327  				break
   328  			}
   329  			s = s[4:]
   330  			if !utf16.IsSurrogate(rune(x)) {
   331  				b = append(b, string(rune(x))...)
   332  				break
   333  			}
   334  
   335  			// Surrogate.
   336  			// See https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates
   337  			if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
   338  				b = append(b, "\\u"...)
   339  				b = append(b, xs...)
   340  				break
   341  			}
   342  			x1, err := strconv.ParseUint(s[2:6], 16, 16)
   343  			if err != nil {
   344  				b = append(b, "\\u"...)
   345  				b = append(b, xs...)
   346  				break
   347  			}
   348  			r := utf16.DecodeRune(rune(x), rune(x1))
   349  			b = append(b, string(r)...)
   350  			s = s[6:]
   351  		default:
   352  			// Unknown escape sequence. Just store it unchanged.
   353  			b = append(b, '\\', ch)
   354  		}
   355  		n = strings.IndexByte(s, '\\')
   356  		if n < 0 {
   357  			b = append(b, s...)
   358  			break
   359  		}
   360  		b = append(b, s[:n]...)
   361  		s = s[n+1:]
   362  	}
   363  	return b2s(b)
   364  }
   365  
   366  // parseRawKey is similar to parseRawString, but is optimized
   367  // for small-sized keys without escape sequences.
   368  func parseRawKey(s string, unquotedKey bool) (string, string, error) {
   369  	for i := 0; i < len(s); i++ {
   370  		if unquotedKey && s[i] == ':' {
   371  			return s[:i], s[i:], nil
   372  		}
   373  		if s[i] == '"' {
   374  			// Fast path.
   375  			return s[:i], s[i+1:], nil
   376  		}
   377  		if s[i] == '\\' {
   378  			// Slow path.
   379  			return parseRawString(s)
   380  		}
   381  	}
   382  	return s, "", fmt.Errorf(`missing closing '"'`)
   383  }
   384  
   385  func parseRawString(s string) (string, string, error) {
   386  	n := strings.IndexByte(s, '"')
   387  	if n < 0 {
   388  		return s, "", fmt.Errorf(`missing closing '"'`)
   389  	}
   390  	if n == 0 || s[n-1] != '\\' {
   391  		// Fast path. No escaped ".
   392  		return s[:n], s[n+1:], nil
   393  	}
   394  
   395  	// Slow path - possible escaped " found.
   396  	ss := s
   397  	for {
   398  		i := n - 1
   399  		for i > 0 && s[i-1] == '\\' {
   400  			i--
   401  		}
   402  		if uint(n-i)%2 == 0 {
   403  			return ss[:len(ss)-len(s)+n], s[n+1:], nil
   404  		}
   405  		s = s[n+1:]
   406  
   407  		n = strings.IndexByte(s, '"')
   408  		if n < 0 {
   409  			return ss, "", fmt.Errorf(`missing closing '"'`)
   410  		}
   411  		if n == 0 || s[n-1] != '\\' {
   412  			return ss[:len(ss)-len(s)+n], s[n+1:], nil
   413  		}
   414  	}
   415  }
   416  
   417  func parseRawNumber(s string) (string, string, error) {
   418  	// The caller must ensure len(s) > 0
   419  
   420  	// Find the end of the number.
   421  	for i := 0; i < len(s); i++ {
   422  		ch := s[i]
   423  		if (ch >= '0' && ch <= '9') || ch == '.' || ch == '-' || ch == 'e' || ch == 'E' || ch == '+' {
   424  			continue
   425  		}
   426  		if i == 0 {
   427  			return "", s, fmt.Errorf("unexpected char: %q", s[:1])
   428  		}
   429  		ns := s[:i]
   430  		s = s[i:]
   431  		return ns, s, nil
   432  	}
   433  	return s, "", nil
   434  }
   435  
   436  // Object represents JSON object.
   437  //
   438  // Object cannot be used from concurrent goroutines.
   439  // Use per-goroutine parsers or ParserPool instead.
   440  type Object struct {
   441  	kvs           []kv
   442  	keysUnescaped bool
   443  }
   444  
   445  func (o *Object) reset() {
   446  	o.kvs = o.kvs[:0]
   447  	o.keysUnescaped = false
   448  }
   449  
   450  // MarshalTo appends marshaled o to dst and returns the result.
   451  func (o *Object) MarshalTo(dst []byte) []byte {
   452  	dst = append(dst, '{')
   453  	for i, kv := range o.kvs {
   454  		if o.keysUnescaped {
   455  			dst = escapeString(dst, kv.k)
   456  		} else {
   457  			dst = append(dst, '"')
   458  			dst = append(dst, kv.k...)
   459  			dst = append(dst, '"')
   460  		}
   461  		dst = append(dst, ':')
   462  		dst = kv.v.MarshalTo(dst)
   463  		if i != len(o.kvs)-1 {
   464  			dst = append(dst, ',')
   465  		}
   466  	}
   467  	dst = append(dst, '}')
   468  	return dst
   469  }
   470  
   471  // String returns string representation for the o.
   472  //
   473  // This function is for debugging purposes only. It isn't optimized for speed.
   474  // See MarshalTo instead.
   475  func (o *Object) String() string {
   476  	b := o.MarshalTo(nil)
   477  	// It is safe converting b to string without allocation, since b is no longer
   478  	// reachable after this line.
   479  	return b2s(b)
   480  }
   481  
   482  func (o *Object) getKV() *kv {
   483  	if cap(o.kvs) > len(o.kvs) {
   484  		o.kvs = o.kvs[:len(o.kvs)+1]
   485  	} else {
   486  		o.kvs = append(o.kvs, kv{})
   487  	}
   488  	return &o.kvs[len(o.kvs)-1]
   489  }
   490  
   491  func (o *Object) unescapeKeys() {
   492  	if o.keysUnescaped {
   493  		return
   494  	}
   495  	for i := range o.kvs {
   496  		kv := &o.kvs[i]
   497  		kv.k = unescapeStringBestEffort(kv.k)
   498  	}
   499  	o.keysUnescaped = true
   500  }
   501  
   502  // Len returns the number of items in the o.
   503  func (o *Object) Len() int {
   504  	return len(o.kvs)
   505  }
   506  
   507  // Get returns the value for the given key in the o.
   508  //
   509  // Returns nil if the value for the given key isn't found.
   510  //
   511  // The returned value is valid until Parse is called on the Parser returned o.
   512  func (o *Object) Get(key string) *Value {
   513  	if !o.keysUnescaped && strings.IndexByte(key, '\\') < 0 {
   514  		// Fast path - try searching for the key without object keys unescaping.
   515  		for _, kv := range o.kvs {
   516  			if kv.k == key {
   517  				return kv.v
   518  			}
   519  		}
   520  	}
   521  
   522  	// Slow path - unescape object keys.
   523  	o.unescapeKeys()
   524  
   525  	for _, kv := range o.kvs {
   526  		if kv.k == key {
   527  			return kv.v
   528  		}
   529  	}
   530  	return nil
   531  }
   532  
   533  // Visit calls f for each item in the o in the original order
   534  // of the parsed JSON.
   535  //
   536  // f cannot hold key and/or v after returning.
   537  func (o *Object) Visit(f func(key []byte, v *Value)) {
   538  	if o == nil {
   539  		return
   540  	}
   541  
   542  	o.unescapeKeys()
   543  
   544  	for _, kv := range o.kvs {
   545  		f(s2b(kv.k), kv.v)
   546  	}
   547  }
   548  
   549  // Value represents any JSON value.
   550  //
   551  // Call Type in order to determine the actual type of the JSON value.
   552  //
   553  // Value cannot be used from concurrent goroutines.
   554  // Use per-goroutine parsers or ParserPool instead.
   555  type Value struct {
   556  	o Object
   557  	a []*Value
   558  	s string
   559  	t Type
   560  }
   561  
   562  // MarshalTo appends marshaled v to dst and returns the result.
   563  func (v *Value) MarshalTo(dst []byte) []byte {
   564  	switch v.t {
   565  	case typeRawString:
   566  		dst = append(dst, '"')
   567  		dst = append(dst, v.s...)
   568  		dst = append(dst, '"')
   569  		return dst
   570  	case TypeObject:
   571  		return v.o.MarshalTo(dst)
   572  	case TypeArray:
   573  		dst = append(dst, '[')
   574  		for i, vv := range v.a {
   575  			dst = vv.MarshalTo(dst)
   576  			if i != len(v.a)-1 {
   577  				dst = append(dst, ',')
   578  			}
   579  		}
   580  		dst = append(dst, ']')
   581  		return dst
   582  	case TypeString:
   583  		return escapeString(dst, v.s)
   584  	case TypeNumber:
   585  		return append(dst, v.s...)
   586  	case TypeTrue:
   587  		return append(dst, "true"...)
   588  	case TypeFalse:
   589  		return append(dst, "false"...)
   590  	case TypeNull:
   591  		return append(dst, "null"...)
   592  	default:
   593  		panic(fmt.Errorf("BUG: unexpected Value type: %d", v.t))
   594  	}
   595  }
   596  
   597  // String returns string representation of the v.
   598  //
   599  // The function is for debugging purposes only. It isn't optimized for speed.
   600  // See MarshalTo instead.
   601  //
   602  // Don't confuse this function with StringBytes, which must be called
   603  // for obtaining the underlying JSON string for the v.
   604  func (v *Value) String() string {
   605  	b := v.MarshalTo(nil)
   606  	// It is safe converting b to string without allocation, since b is no longer
   607  	// reachable after this line.
   608  	return b2s(b)
   609  }
   610  
   611  // Type represents JSON type.
   612  type Type int
   613  
   614  const (
   615  	// TypeNull is JSON null.
   616  	TypeNull Type = 0
   617  
   618  	// TypeObject is JSON object type.
   619  	TypeObject Type = 1
   620  
   621  	// TypeArray is JSON array type.
   622  	TypeArray Type = 2
   623  
   624  	// TypeString is JSON string type.
   625  	TypeString Type = 3
   626  
   627  	// TypeNumber is JSON number type.
   628  	TypeNumber Type = 4
   629  
   630  	// TypeTrue is JSON true.
   631  	TypeTrue Type = 5
   632  
   633  	// TypeFalse is JSON false.
   634  	TypeFalse Type = 6
   635  
   636  	typeRawString Type = 7
   637  )
   638  
   639  // String returns string representation of t.
   640  func (t Type) String() string {
   641  	switch t {
   642  	case TypeObject:
   643  		return "object"
   644  	case TypeArray:
   645  		return "array"
   646  	case TypeString:
   647  		return "string"
   648  	case TypeNumber:
   649  		return "number"
   650  	case TypeTrue:
   651  		return "true"
   652  	case TypeFalse:
   653  		return "false"
   654  	case TypeNull:
   655  		return "null"
   656  
   657  	// typeRawString is skipped intentionally,
   658  	// since it shouldn't be visible to user.
   659  	default:
   660  		panic(fmt.Errorf("BUG: unknown Value type: %d", t))
   661  	}
   662  }
   663  
   664  // Type returns the type of the v.
   665  func (v *Value) Type() Type {
   666  	if v.t == typeRawString {
   667  		v.s = unescapeStringBestEffort(v.s)
   668  		v.t = TypeString
   669  	}
   670  	return v.t
   671  }
   672  
   673  // Exists returns true if the field exists for the given keys path.
   674  //
   675  // Array indexes may be represented as decimal numbers in keys.
   676  func (v *Value) Exists(keys ...string) bool {
   677  	v = v.Get(keys...)
   678  	return v != nil
   679  }
   680  
   681  // Get returns value by the given keys path.
   682  //
   683  // Array indexes may be represented as decimal numbers in keys.
   684  //
   685  // nil is returned for non-existing keys path.
   686  //
   687  // The returned value is valid until Parse is called on the Parser returned v.
   688  func (v *Value) Get(keys ...string) *Value {
   689  	if v == nil {
   690  		return nil
   691  	}
   692  	for _, key := range keys {
   693  		if v.t == TypeObject {
   694  			v = v.o.Get(key)
   695  			if v == nil {
   696  				return nil
   697  			}
   698  		} else if v.t == TypeArray {
   699  			n, err := strconv.Atoi(key)
   700  			if err != nil || n < 0 || n >= len(v.a) {
   701  				return nil
   702  			}
   703  			v = v.a[n]
   704  		} else {
   705  			return nil
   706  		}
   707  	}
   708  	return v
   709  }
   710  
   711  // GetObject returns object value by the given keys path.
   712  //
   713  // Array indexes may be represented as decimal numbers in keys.
   714  //
   715  // nil is returned for non-existing keys path or for invalid value type.
   716  //
   717  // The returned object is valid until Parse is called on the Parser returned v.
   718  func (v *Value) GetObject(keys ...string) *Object {
   719  	v = v.Get(keys...)
   720  	if v == nil || v.t != TypeObject {
   721  		return nil
   722  	}
   723  	return &v.o
   724  }
   725  
   726  // GetArray returns array value by the given keys path.
   727  //
   728  // Array indexes may be represented as decimal numbers in keys.
   729  //
   730  // nil is returned for non-existing keys path or for invalid value type.
   731  //
   732  // The returned array is valid until Parse is called on the Parser returned v.
   733  func (v *Value) GetArray(keys ...string) []*Value {
   734  	v = v.Get(keys...)
   735  	if v == nil || v.t != TypeArray {
   736  		return nil
   737  	}
   738  	return v.a
   739  }
   740  
   741  // GetFloat64 returns float64 value by the given keys path.
   742  //
   743  // Array indexes may be represented as decimal numbers in keys.
   744  //
   745  // 0 is returned for non-existing keys path or for invalid value type.
   746  func (v *Value) GetFloat64(keys ...string) float64 {
   747  	v = v.Get(keys...)
   748  	if v == nil || v.Type() != TypeNumber {
   749  		return 0
   750  	}
   751  	return ParseBestEffort(v.s)
   752  }
   753  
   754  // GetInt returns int value by the given keys path.
   755  //
   756  // Array indexes may be represented as decimal numbers in keys.
   757  //
   758  // 0 is returned for non-existing keys path or for invalid value type.
   759  func (v *Value) GetInt(keys ...string) int {
   760  	v = v.Get(keys...)
   761  	if v == nil || v.Type() != TypeNumber {
   762  		return 0
   763  	}
   764  	n := ParseInt64BestEffort(v.s)
   765  	nn := int(n)
   766  	if int64(nn) != n {
   767  		return 0
   768  	}
   769  	return nn
   770  }
   771  
   772  // GetUint returns uint value by the given keys path.
   773  //
   774  // Array indexes may be represented as decimal numbers in keys.
   775  //
   776  // 0 is returned for non-existing keys path or for invalid value type.
   777  func (v *Value) GetUint(keys ...string) uint {
   778  	v = v.Get(keys...)
   779  	if v == nil || v.Type() != TypeNumber {
   780  		return 0
   781  	}
   782  	n := ParseUint64BestEffort(v.s)
   783  	nn := uint(n)
   784  	if uint64(nn) != n {
   785  		return 0
   786  	}
   787  	return nn
   788  }
   789  
   790  // GetInt64 returns int64 value by the given keys path.
   791  //
   792  // Array indexes may be represented as decimal numbers in keys.
   793  //
   794  // 0 is returned for non-existing keys path or for invalid value type.
   795  func (v *Value) GetInt64(keys ...string) int64 {
   796  	v = v.Get(keys...)
   797  	if v == nil || v.Type() != TypeNumber {
   798  		return 0
   799  	}
   800  	return ParseInt64BestEffort(v.s)
   801  }
   802  
   803  // GetUint64 returns uint64 value by the given keys path.
   804  //
   805  // Array indexes may be represented as decimal numbers in keys.
   806  //
   807  // 0 is returned for non-existing keys path or for invalid value type.
   808  func (v *Value) GetUint64(keys ...string) uint64 {
   809  	v = v.Get(keys...)
   810  	if v == nil || v.Type() != TypeNumber {
   811  		return 0
   812  	}
   813  	return ParseUint64BestEffort(v.s)
   814  }
   815  
   816  // GetStringBytes returns string value by the given keys path.
   817  //
   818  // Array indexes may be represented as decimal numbers in keys.
   819  //
   820  // nil is returned for non-existing keys path or for invalid value type.
   821  //
   822  // The returned string is valid until Parse is called on the Parser returned v.
   823  func (v *Value) GetStringBytes(keys ...string) []byte {
   824  	v = v.Get(keys...)
   825  	if v == nil || v.Type() != TypeString {
   826  		return nil
   827  	}
   828  	return s2b(v.s)
   829  }
   830  
   831  func (v *Value) GetString(key string) string {
   832  	val := v.Get(key)
   833  	if val == nil {
   834  		return ""
   835  	}
   836  	return val.s
   837  }
   838  
   839  // GetBool returns bool value by the given keys path.
   840  //
   841  // Array indexes may be represented as decimal numbers in keys.
   842  //
   843  // false is returned for non-existing keys path or for invalid value type.
   844  func (v *Value) GetBool(keys ...string) bool {
   845  	v = v.Get(keys...)
   846  	if v != nil && v.t == TypeTrue {
   847  		return true
   848  	}
   849  	return false
   850  }
   851  
   852  // Object returns the underlying JSON object for the v.
   853  //
   854  // The returned object is valid until Parse is called on the Parser returned v.
   855  //
   856  // Use GetObject if you don't need error handling.
   857  func (v *Value) Object() (*Object, error) {
   858  	if v.t != TypeObject {
   859  		return nil, fmt.Errorf("value doesn't contain object; it contains %s", v.Type())
   860  	}
   861  	return &v.o, nil
   862  }
   863  
   864  // Array returns the underlying JSON array for the v.
   865  //
   866  // The returned array is valid until Parse is called on the Parser returned v.
   867  //
   868  // Use GetArray if you don't need error handling.
   869  func (v *Value) Array() ([]*Value, error) {
   870  	if v.t != TypeArray {
   871  		return nil, fmt.Errorf("value doesn't contain array; it contains %s", v.Type())
   872  	}
   873  	return v.a, nil
   874  }
   875  
   876  // StringBytes returns the underlying JSON string for the v.
   877  //
   878  // The returned string is valid until Parse is called on the Parser returned v.
   879  //
   880  // Use GetStringBytes if you don't need error handling.
   881  func (v *Value) StringBytes() ([]byte, error) {
   882  	if v.Type() != TypeString {
   883  		return nil, fmt.Errorf("value doesn't contain string; it contains %s", v.Type())
   884  	}
   885  	return s2b(v.s), nil
   886  }
   887  
   888  // Float64 returns the underlying JSON number for the v.
   889  //
   890  // Use GetFloat64 if you don't need error handling.
   891  func (v *Value) Float64() (float64, error) {
   892  	if v.Type() != TypeNumber {
   893  		return 0, fmt.Errorf("value doesn't contain number; it contains %s", v.Type())
   894  	}
   895  	f := ParseBestEffort(v.s)
   896  	return f, nil
   897  }
   898  
   899  // Int returns the underlying JSON int for the v.
   900  //
   901  // Use GetInt if you don't need error handling.
   902  func (v *Value) Int() (int, error) {
   903  	if v.Type() != TypeNumber {
   904  		return 0, fmt.Errorf("value doesn't contain number; it contains %s", v.Type())
   905  	}
   906  	n := ParseInt64BestEffort(v.s)
   907  	if n == 0 && v.s != "0" {
   908  		return 0, fmt.Errorf("cannot parse int %q", v.s)
   909  	}
   910  	nn := int(n)
   911  	if int64(nn) != n {
   912  		return 0, fmt.Errorf("number %q doesn't fit int", v.s)
   913  	}
   914  	return nn, nil
   915  }
   916  
   917  // Uint returns the underlying JSON uint for the v.
   918  //
   919  // Use GetInt if you don't need error handling.
   920  func (v *Value) Uint() (uint, error) {
   921  	if v.Type() != TypeNumber {
   922  		return 0, fmt.Errorf("value doesn't contain number; it contains %s", v.Type())
   923  	}
   924  	n := ParseUint64BestEffort(v.s)
   925  	if n == 0 && v.s != "0" {
   926  		return 0, fmt.Errorf("cannot parse uint %q", v.s)
   927  	}
   928  	nn := uint(n)
   929  	if uint64(nn) != n {
   930  		return 0, fmt.Errorf("number %q doesn't fit uint", v.s)
   931  	}
   932  	return nn, nil
   933  }
   934  
   935  // Int64 returns the underlying JSON int64 for the v.
   936  //
   937  // Use GetInt64 if you don't need error handling.
   938  func (v *Value) Int64() (int64, error) {
   939  	if v.Type() != TypeNumber {
   940  		return 0, fmt.Errorf("value doesn't contain number; it contains %s", v.Type())
   941  	}
   942  	n := ParseInt64BestEffort(v.s)
   943  	if n == 0 && v.s != "0" {
   944  		return 0, fmt.Errorf("cannot parse int64 %q", v.s)
   945  	}
   946  	return n, nil
   947  }
   948  
   949  // Uint64 returns the underlying JSON uint64 for the v.
   950  //
   951  // Use GetInt64 if you don't need error handling.
   952  func (v *Value) Uint64() (uint64, error) {
   953  	if v.Type() != TypeNumber {
   954  		return 0, fmt.Errorf("value doesn't contain number; it contains %s", v.Type())
   955  	}
   956  	n := ParseUint64BestEffort(v.s)
   957  	if n == 0 && v.s != "0" {
   958  		return 0, fmt.Errorf("cannot parse uint64 %q", v.s)
   959  	}
   960  	return n, nil
   961  }
   962  
   963  // Bool returns the underlying JSON bool for the v.
   964  //
   965  // Use GetBool if you don't need error handling.
   966  func (v *Value) Bool() (bool, error) {
   967  	if v.t == TypeTrue {
   968  		return true, nil
   969  	}
   970  	if v.t == TypeFalse {
   971  		return false, nil
   972  	}
   973  	return false, fmt.Errorf("value doesn't contain bool; it contains %s", v.Type())
   974  }
   975  
   976  var (
   977  	valueTrue  = &Value{t: TypeTrue}
   978  	valueFalse = &Value{t: TypeFalse}
   979  	valueNull  = &Value{t: TypeNull}
   980  )