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://blog.golang.org/2011/01/json-and-go.html
25 // Marshal returns the JSON encoding of v.
27 // Marshal traverses the value v recursively.
28 // If an encountered value implements the Marshaler interface
29 // and is not a nil pointer, Marshal calls its MarshalJSON method
30 // to produce JSON. The nil pointer exception is not strictly necessary
31 // but mimics a similar, necessary exception in the behavior of
34 // Otherwise, Marshal uses the following type-dependent default encodings:
36 // Boolean values encode as JSON booleans.
38 // Floating point and integer values encode as JSON numbers.
40 // String values encode as JSON strings, with each invalid UTF-8 sequence
41 // replaced by the encoding of the Unicode replacement character U+FFFD.
42 // The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e"
43 // to keep some browsers from misinterpreting JSON output as HTML.
45 // Array and slice values encode as JSON arrays, except that
46 // []byte encodes as a base64-encoded string.
48 // Struct values encode as JSON objects. Each exported struct field
49 // becomes a member of the object unless
50 // - the field's tag is "-", or
51 // - the field is empty and its tag specifies the "omitempty" option.
52 // The empty values are false, 0, any
53 // nil pointer or interface value, and any array, slice, map, or string of
54 // length zero. The object's default key string is the struct field name
55 // but can be specified in the struct field's tag value. The "json" key in
56 // struct field's tag value is the key name, followed by an optional comma
57 // and options. Examples:
59 // // Field is ignored by this package.
60 // Field int `json:"-"`
62 // // Field appears in JSON as key "myName".
63 // Field int `json:"myName"`
65 // // Field appears in JSON as key "myName" and
66 // // the field is omitted from the object if its value is empty,
67 // // as defined above.
68 // Field int `json:"myName,omitempty"`
70 // // Field appears in JSON as key "Field" (the default), but
71 // // the field is skipped if empty.
72 // // Note the leading comma.
73 // Field int `json:",omitempty"`
75 // The "string" option signals that a field is stored as JSON inside a
76 // JSON-encoded string. This extra level of encoding is sometimes
77 // used when communicating with JavaScript programs:
79 // Int64String int64 `json:",string"`
81 // The key name will be used if it's a non-empty string consisting of
82 // only Unicode letters, digits, dollar signs, percent signs, hyphens,
83 // underscores and slashes.
85 // Map values encode as JSON objects.
86 // The map's key type must be string; the object keys are used directly
89 // Pointer values encode as the value pointed to.
90 // A nil pointer encodes as the null JSON object.
92 // Interface values encode as the value contained in the interface.
93 // A nil interface value encodes as the null JSON object.
95 // Channel, complex, and function values cannot be encoded in JSON.
96 // Attempting to encode such a value causes Marshal to return
97 // an InvalidTypeError.
99 // JSON cannot represent cyclic data structures and Marshal does not
100 // handle them. Passing cyclic structures to Marshal will result in
101 // an infinite recursion.
103 func Marshal(v interface{}) ([]byte, error) {
109 return e.Bytes(), nil
112 // MarshalIndent is like Marshal but applies Indent to format the output.
113 func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
119 err = Indent(&buf, b, prefix, indent)
123 return buf.Bytes(), nil
126 // MarshalForHTML is like Marshal but applies HTMLEscape to the output.
127 func MarshalForHTML(v interface{}) ([]byte, error) {
134 return buf.Bytes(), nil
137 // HTMLEscape appends to dst the JSON-encoded src with <, >, and &
138 // characters inside string literals changed to \u003c, \u003e, \u0026
139 // so that the JSON will be safe to embed inside HTML <script> tags.
140 // For historical reasons, web browsers don't honor standard HTML
141 // escaping within <script> tags, so an alternative JSON encoding must
143 func HTMLEscape(dst *bytes.Buffer, src []byte) {
144 // < > & can only appear in string literals,
145 // so just scan the string one byte at a time.
147 for i, c := range src {
148 if c == '<' || c == '>' || c == '&' {
150 dst.Write(src[start:i])
152 dst.WriteString(`\u00`)
153 dst.WriteByte(hex[c>>4])
154 dst.WriteByte(hex[c&0xF])
158 if start < len(src) {
159 dst.Write(src[start:])
163 // Marshaler is the interface implemented by objects that
164 // can marshal themselves into valid JSON.
165 type Marshaler interface {
166 MarshalJSON() ([]byte, error)
169 type UnsupportedTypeError struct {
173 func (e *UnsupportedTypeError) Error() string {
174 return "json: unsupported type: " + e.Type.String()
177 type UnsupportedValueError struct {
182 func (e *UnsupportedValueError) Error() string {
183 return "json: unsupported value: " + e.Str
186 type InvalidUTF8Error struct {
190 func (e *InvalidUTF8Error) Error() string {
191 return "json: invalid UTF-8 in string: " + strconv.Quote(e.S)
194 type MarshalerError struct {
199 func (e *MarshalerError) Error() string {
200 return "json: error calling MarshalJSON for type " + e.Type.String() + ": " + e.Err.Error()
203 type interfaceOrPtrValue interface {
208 var hex = "0123456789abcdef"
210 // An encodeState encodes JSON into a bytes.Buffer.
211 type encodeState struct {
212 bytes.Buffer // accumulated output
216 func (e *encodeState) marshal(v interface{}) (err error) {
218 if r := recover(); r != nil {
219 if _, ok := r.(runtime.Error); ok {
225 e.reflectValue(reflect.ValueOf(v))
229 func (e *encodeState) error(err error) {
233 var byteSliceType = reflect.TypeOf([]byte(nil))
235 func isEmptyValue(v reflect.Value) bool {
237 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
241 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
243 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
245 case reflect.Float32, reflect.Float64:
246 return v.Float() == 0
247 case reflect.Interface, reflect.Ptr:
253 func (e *encodeState) reflectValue(v reflect.Value) {
254 e.reflectValueQuoted(v, false)
257 // reflectValueQuoted writes the value in v to the output.
258 // If quoted is true, the serialization is wrapped in a JSON string.
259 func (e *encodeState) reflectValueQuoted(v reflect.Value, quoted bool) {
261 e.WriteString("null")
265 m, ok := v.Interface().(Marshaler)
267 // T doesn't match the interface. Check against *T too.
268 if v.Kind() != reflect.Ptr && v.CanAddr() {
269 m, ok = v.Addr().Interface().(Marshaler)
275 if ok && (v.Kind() != reflect.Ptr || !v.IsNil()) {
276 b, err := m.MarshalJSON()
278 // copy JSON into buffer, checking validity.
279 err = Compact(&e.Buffer, b)
282 e.error(&MarshalerError{v.Type(), err})
287 writeString := (*encodeState).WriteString
289 writeString = (*encodeState).string
296 writeString(e, "true")
298 writeString(e, "false")
301 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
302 b := strconv.AppendInt(e.scratch[:0], v.Int(), 10)
304 writeString(e, string(b))
308 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
309 b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10)
311 writeString(e, string(b))
315 case reflect.Float32, reflect.Float64:
317 if math.IsInf(f, 0) || math.IsNaN(f) {
318 e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, v.Type().Bits())})
320 b := strconv.AppendFloat(e.scratch[:0], f, 'g', -1, v.Type().Bits())
322 writeString(e, string(b))
328 sb, err := Marshal(v.String())
340 for _, ef := range encodeFields(v.Type()) {
341 fieldValue := v.Field(ef.i)
342 if ef.omitEmpty && isEmptyValue(fieldValue) {
352 e.reflectValueQuoted(fieldValue, ef.quoted)
357 if v.Type().Key().Kind() != reflect.String {
358 e.error(&UnsupportedTypeError{v.Type()})
361 e.WriteString("null")
365 var sv stringValues = v.MapKeys()
367 for i, k := range sv {
373 e.reflectValue(v.MapIndex(k))
379 e.WriteString("null")
382 if v.Type().Elem().Kind() == reflect.Uint8 {
383 // Byte slices get special treatment; arrays don't.
387 // for small buffers, using Encode directly is much faster.
388 dst := make([]byte, base64.StdEncoding.EncodedLen(len(s)))
389 base64.StdEncoding.Encode(dst, s)
392 // for large buffers, avoid unnecessary extra temporary
394 enc := base64.NewEncoder(base64.StdEncoding, e)
401 // Slices can be marshalled as nil, but otherwise are handled
407 for i := 0; i < n; i++ {
411 e.reflectValue(v.Index(i))
415 case reflect.Interface, reflect.Ptr:
417 e.WriteString("null")
420 e.reflectValue(v.Elem())
423 e.error(&UnsupportedTypeError{v.Type()})
428 func isValidTag(s string) bool {
432 for _, c := range s {
434 case '$', '-', '_', '/', '%':
437 if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
445 // stringValues is a slice of reflect.Value holding *reflect.StringValue.
446 // It implements the methods to sort by string.
447 type stringValues []reflect.Value
449 func (sv stringValues) Len() int { return len(sv) }
450 func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
451 func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) }
452 func (sv stringValues) get(i int) string { return sv[i].String() }
454 func (e *encodeState) string(s string) (int, error) {
458 for i := 0; i < len(s); {
459 if b := s[i]; b < utf8.RuneSelf {
460 if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' {
465 e.WriteString(s[start:i])
478 // This encodes bytes < 0x20 except for \n and \r,
479 // as well as < and >. The latter are escaped because they
480 // can lead to security holes when user-controlled strings
481 // are rendered into JSON and served to some browsers.
482 e.WriteString(`\u00`)
483 e.WriteByte(hex[b>>4])
484 e.WriteByte(hex[b&0xF])
490 c, size := utf8.DecodeRuneInString(s[i:])
491 if c == utf8.RuneError && size == 1 {
492 e.error(&InvalidUTF8Error{s})
497 e.WriteString(s[start:])
500 return e.Len() - len0, nil
503 // encodeField contains information about how to encode a field of a
505 type encodeField struct {
506 i int // field index in struct
513 typeCacheLock sync.RWMutex
514 encodeFieldsCache = make(map[reflect.Type][]encodeField)
517 // encodeFields returns a slice of encodeField for a given
519 func encodeFields(t reflect.Type) []encodeField {
520 typeCacheLock.RLock()
521 fs, ok := encodeFieldsCache[t]
522 typeCacheLock.RUnlock()
528 defer typeCacheLock.Unlock()
529 fs, ok = encodeFieldsCache[t]
536 for i := 0; i < n; i++ {
545 tv := f.Tag.Get("json")
550 name, opts := parseTag(tv)
551 if isValidTag(name) {
554 ef.omitEmpty = opts.Contains("omitempty")
555 ef.quoted = opts.Contains("string")
559 encodeFieldsCache[t] = fs