1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package json implements encoding and decoding of JSON objects as defined in
8 // See "JSON and Go" for an introduction to this package:
9 // http://golang.org/doc/articles/json_and_go.html
26 // Marshal returns the JSON encoding of v.
28 // Marshal traverses the value v recursively.
29 // If an encountered value implements the Marshaler interface
30 // and is not a nil pointer, Marshal calls its MarshalJSON method
31 // to produce JSON. The nil pointer exception is not strictly necessary
32 // but mimics a similar, necessary exception in the behavior of
35 // Otherwise, Marshal uses the following type-dependent default encodings:
37 // Boolean values encode as JSON booleans.
39 // Floating point and integer values encode as JSON numbers.
41 // String values encode as JSON strings, with each invalid UTF-8 sequence
42 // replaced by the encoding of the Unicode replacement character U+FFFD.
43 // The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e"
44 // to keep some browsers from misinterpreting JSON output as HTML.
46 // Array and slice values encode as JSON arrays, except that
47 // []byte encodes as a base64-encoded string, and a nil slice
48 // encodes as the null JSON object.
50 // Struct values encode as JSON objects. Each exported struct field
51 // becomes a member of the object unless
52 // - the field's tag is "-", or
53 // - the field is empty and its tag specifies the "omitempty" option.
54 // The empty values are false, 0, any
55 // nil pointer or interface value, and any array, slice, map, or string of
56 // length zero. The object's default key string is the struct field name
57 // but can be specified in the struct field's tag value. The "json" key in
58 // struct field's tag value is the key name, followed by an optional comma
59 // and options. Examples:
61 // // Field is ignored by this package.
62 // Field int `json:"-"`
64 // // Field appears in JSON as key "myName".
65 // Field int `json:"myName"`
67 // // Field appears in JSON as key "myName" and
68 // // the field is omitted from the object if its value is empty,
69 // // as defined above.
70 // Field int `json:"myName,omitempty"`
72 // // Field appears in JSON as key "Field" (the default), but
73 // // the field is skipped if empty.
74 // // Note the leading comma.
75 // Field int `json:",omitempty"`
77 // The "string" option signals that a field is stored as JSON inside a
78 // JSON-encoded string. This extra level of encoding is sometimes
79 // used when communicating with JavaScript programs:
81 // Int64String int64 `json:",string"`
83 // The key name will be used if it's a non-empty string consisting of
84 // only Unicode letters, digits, dollar signs, percent signs, hyphens,
85 // underscores and slashes.
87 // Map values encode as JSON objects.
88 // The map's key type must be string; the object keys are used directly
91 // Pointer values encode as the value pointed to.
92 // A nil pointer encodes as the null JSON object.
94 // Interface values encode as the value contained in the interface.
95 // A nil interface value encodes as the null JSON object.
97 // Channel, complex, and function values cannot be encoded in JSON.
98 // Attempting to encode such a value causes Marshal to return
99 // an UnsupportedTypeError.
101 // JSON cannot represent cyclic data structures and Marshal does not
102 // handle them. Passing cyclic structures to Marshal will result in
103 // an infinite recursion.
105 func Marshal(v interface{}) ([]byte, error) {
111 return e.Bytes(), nil
114 // MarshalIndent is like Marshal but applies Indent to format the output.
115 func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
121 err = Indent(&buf, b, prefix, indent)
125 return buf.Bytes(), nil
128 // HTMLEscape appends to dst the JSON-encoded src with <, >, and &
129 // characters inside string literals changed to \u003c, \u003e, \u0026
130 // so that the JSON will be safe to embed inside HTML <script> tags.
131 // For historical reasons, web browsers don't honor standard HTML
132 // escaping within <script> tags, so an alternative JSON encoding must
134 func HTMLEscape(dst *bytes.Buffer, src []byte) {
135 // < > & can only appear in string literals,
136 // so just scan the string one byte at a time.
138 for i, c := range src {
139 if c == '<' || c == '>' || c == '&' {
141 dst.Write(src[start:i])
143 dst.WriteString(`\u00`)
144 dst.WriteByte(hex[c>>4])
145 dst.WriteByte(hex[c&0xF])
149 if start < len(src) {
150 dst.Write(src[start:])
154 // Marshaler is the interface implemented by objects that
155 // can marshal themselves into valid JSON.
156 type Marshaler interface {
157 MarshalJSON() ([]byte, error)
160 // An UnsupportedTypeError is returned by Marshal when attempting
161 // to encode an unsupported value type.
162 type UnsupportedTypeError struct {
166 func (e *UnsupportedTypeError) Error() string {
167 return "json: unsupported type: " + e.Type.String()
170 type UnsupportedValueError struct {
175 func (e *UnsupportedValueError) Error() string {
176 return "json: unsupported value: " + e.Str
179 type InvalidUTF8Error struct {
183 func (e *InvalidUTF8Error) Error() string {
184 return "json: invalid UTF-8 in string: " + strconv.Quote(e.S)
187 type MarshalerError struct {
192 func (e *MarshalerError) Error() string {
193 return "json: error calling MarshalJSON for type " + e.Type.String() + ": " + e.Err.Error()
196 var hex = "0123456789abcdef"
198 // An encodeState encodes JSON into a bytes.Buffer.
199 type encodeState struct {
200 bytes.Buffer // accumulated output
204 func (e *encodeState) marshal(v interface{}) (err error) {
206 if r := recover(); r != nil {
207 if _, ok := r.(runtime.Error); ok {
213 e.reflectValue(reflect.ValueOf(v))
217 func (e *encodeState) error(err error) {
221 var byteSliceType = reflect.TypeOf([]byte(nil))
223 func isEmptyValue(v reflect.Value) bool {
225 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
229 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
231 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
233 case reflect.Float32, reflect.Float64:
234 return v.Float() == 0
235 case reflect.Interface, reflect.Ptr:
241 func (e *encodeState) reflectValue(v reflect.Value) {
242 e.reflectValueQuoted(v, false)
245 // reflectValueQuoted writes the value in v to the output.
246 // If quoted is true, the serialization is wrapped in a JSON string.
247 func (e *encodeState) reflectValueQuoted(v reflect.Value, quoted bool) {
249 e.WriteString("null")
253 m, ok := v.Interface().(Marshaler)
255 // T doesn't match the interface. Check against *T too.
256 if v.Kind() != reflect.Ptr && v.CanAddr() {
257 m, ok = v.Addr().Interface().(Marshaler)
263 if ok && (v.Kind() != reflect.Ptr || !v.IsNil()) {
264 b, err := m.MarshalJSON()
266 // copy JSON into buffer, checking validity.
267 err = compact(&e.Buffer, b, true)
270 e.error(&MarshalerError{v.Type(), err})
275 writeString := (*encodeState).WriteString
277 writeString = (*encodeState).string
284 writeString(e, "true")
286 writeString(e, "false")
289 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
290 b := strconv.AppendInt(e.scratch[:0], v.Int(), 10)
292 writeString(e, string(b))
296 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
297 b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10)
299 writeString(e, string(b))
303 case reflect.Float32, reflect.Float64:
305 if math.IsInf(f, 0) || math.IsNaN(f) {
306 e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, v.Type().Bits())})
308 b := strconv.AppendFloat(e.scratch[:0], f, 'g', -1, v.Type().Bits())
310 writeString(e, string(b))
316 sb, err := Marshal(v.String())
328 for _, ef := range encodeFields(v.Type()) {
329 fieldValue := v.Field(ef.i)
330 if ef.omitEmpty && isEmptyValue(fieldValue) {
340 e.reflectValueQuoted(fieldValue, ef.quoted)
345 if v.Type().Key().Kind() != reflect.String {
346 e.error(&UnsupportedTypeError{v.Type()})
349 e.WriteString("null")
353 var sv stringValues = v.MapKeys()
355 for i, k := range sv {
361 e.reflectValue(v.MapIndex(k))
367 e.WriteString("null")
370 if v.Type().Elem().Kind() == reflect.Uint8 {
371 // Byte slices get special treatment; arrays don't.
375 // for small buffers, using Encode directly is much faster.
376 dst := make([]byte, base64.StdEncoding.EncodedLen(len(s)))
377 base64.StdEncoding.Encode(dst, s)
380 // for large buffers, avoid unnecessary extra temporary
382 enc := base64.NewEncoder(base64.StdEncoding, e)
389 // Slices can be marshalled as nil, but otherwise are handled
395 for i := 0; i < n; i++ {
399 e.reflectValue(v.Index(i))
403 case reflect.Interface, reflect.Ptr:
405 e.WriteString("null")
408 e.reflectValue(v.Elem())
411 e.error(&UnsupportedTypeError{v.Type()})
416 func isValidTag(s string) bool {
420 for _, c := range s {
422 case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~", c):
423 // Backslash and quote chars are reserved, but
424 // otherwise any punctuation chars are allowed
427 if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
435 // stringValues is a slice of reflect.Value holding *reflect.StringValue.
436 // It implements the methods to sort by string.
437 type stringValues []reflect.Value
439 func (sv stringValues) Len() int { return len(sv) }
440 func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
441 func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) }
442 func (sv stringValues) get(i int) string { return sv[i].String() }
444 func (e *encodeState) string(s string) (int, error) {
448 for i := 0; i < len(s); {
449 if b := s[i]; b < utf8.RuneSelf {
450 if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' {
455 e.WriteString(s[start:i])
468 // This encodes bytes < 0x20 except for \n and \r,
469 // as well as < and >. The latter are escaped because they
470 // can lead to security holes when user-controlled strings
471 // are rendered into JSON and served to some browsers.
472 e.WriteString(`\u00`)
473 e.WriteByte(hex[b>>4])
474 e.WriteByte(hex[b&0xF])
480 c, size := utf8.DecodeRuneInString(s[i:])
481 if c == utf8.RuneError && size == 1 {
482 e.error(&InvalidUTF8Error{s})
487 e.WriteString(s[start:])
490 return e.Len() - len0, nil
493 // encodeField contains information about how to encode a field of a
495 type encodeField struct {
496 i int // field index in struct
503 typeCacheLock sync.RWMutex
504 encodeFieldsCache = make(map[reflect.Type][]encodeField)
507 // encodeFields returns a slice of encodeField for a given
509 func encodeFields(t reflect.Type) []encodeField {
510 typeCacheLock.RLock()
511 fs, ok := encodeFieldsCache[t]
512 typeCacheLock.RUnlock()
518 defer typeCacheLock.Unlock()
519 fs, ok = encodeFieldsCache[t]
526 for i := 0; i < n; i++ {
532 // We want to do a better job with these later,
533 // so for now pretend they don't exist.
540 tv := f.Tag.Get("json")
545 name, opts := parseTag(tv)
546 if isValidTag(name) {
549 ef.omitEmpty = opts.Contains("omitempty")
550 ef.quoted = opts.Contains("string")
554 encodeFieldsCache[t] = fs