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
24 // Marshal returns the JSON encoding of v.
26 // Marshal traverses the value v recursively.
27 // If an encountered value implements the Marshaler interface
28 // and is not a nil pointer, Marshal calls its MarshalJSON method
29 // to produce JSON. The nil pointer exception is not strictly necessary
30 // but mimics a similar, necessary exception in the behavior of
33 // Otherwise, Marshal uses the following type-dependent default encodings:
35 // Boolean values encode as JSON booleans.
37 // Floating point and integer values encode as JSON numbers.
39 // String values encode as JSON strings, with each invalid UTF-8 sequence
40 // replaced by the encoding of the Unicode replacement character U+FFFD.
42 // Array and slice values encode as JSON arrays, except that
43 // []byte encodes as a base64-encoded string.
45 // Struct values encode as JSON objects. Each exported struct field
46 // becomes a member of the object unless
47 // - the field's tag is "-", or
48 // - the field is empty and its tag specifies the "omitempty" option.
49 // The empty values are false, 0, any
50 // nil pointer or interface value, and any array, slice, map, or string of
51 // length zero. The object's default key string is the struct field name
52 // but can be specified in the struct field's tag value. The "json" key in
53 // struct field's tag value is the key name, followed by an optional comma
54 // and options. Examples:
56 // // Field is ignored by this package.
57 // Field int `json:"-"`
59 // // Field appears in JSON as key "myName".
60 // Field int `json:"myName"`
62 // // Field appears in JSON as key "myName" and
63 // // the field is omitted from the object if its value is empty,
64 // // as defined above.
65 // Field int `json:"myName,omitempty"`
67 // // Field appears in JSON as key "Field" (the default), but
68 // // the field is skipped if empty.
69 // // Note the leading comma.
70 // Field int `json:",omitempty"`
72 // The "string" option signals that a field is stored as JSON inside a
73 // JSON-encoded string. This extra level of encoding is sometimes
74 // used when communicating with JavaScript programs:
76 // Int64String int64 `json:",string"`
78 // The key name will be used if it's a non-empty string consisting of
79 // only Unicode letters, digits, dollar signs, hyphens, and underscores.
81 // Map values encode as JSON objects.
82 // The map's key type must be string; the object keys are used directly
85 // Pointer values encode as the value pointed to.
86 // A nil pointer encodes as the null JSON object.
88 // Interface values encode as the value contained in the interface.
89 // A nil interface value encodes as the null JSON object.
91 // Channel, complex, and function values cannot be encoded in JSON.
92 // Attempting to encode such a value causes Marshal to return
93 // an InvalidTypeError.
95 // JSON cannot represent cyclic data structures and Marshal does not
96 // handle them. Passing cyclic structures to Marshal will result in
97 // an infinite recursion.
99 func Marshal(v interface{}) ([]byte, error) {
105 return e.Bytes(), nil
108 // MarshalIndent is like Marshal but applies Indent to format the output.
109 func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
115 err = Indent(&buf, b, prefix, indent)
119 return buf.Bytes(), nil
122 // MarshalForHTML is like Marshal but applies HTMLEscape to the output.
123 func MarshalForHTML(v interface{}) ([]byte, error) {
130 return buf.Bytes(), nil
133 // HTMLEscape appends to dst the JSON-encoded src with <, >, and &
134 // characters inside string literals changed to \u003c, \u003e, \u0026
135 // so that the JSON will be safe to embed inside HTML <script> tags.
136 // For historical reasons, web browsers don't honor standard HTML
137 // escaping within <script> tags, so an alternative JSON encoding must
139 func HTMLEscape(dst *bytes.Buffer, src []byte) {
140 // < > & can only appear in string literals,
141 // so just scan the string one byte at a time.
143 for i, c := range src {
144 if c == '<' || c == '>' || c == '&' {
146 dst.Write(src[start:i])
148 dst.WriteString(`\u00`)
149 dst.WriteByte(hex[c>>4])
150 dst.WriteByte(hex[c&0xF])
154 if start < len(src) {
155 dst.Write(src[start:])
159 // Marshaler is the interface implemented by objects that
160 // can marshal themselves into valid JSON.
161 type Marshaler interface {
162 MarshalJSON() ([]byte, error)
165 type UnsupportedTypeError struct {
169 func (e *UnsupportedTypeError) Error() string {
170 return "json: unsupported type: " + e.Type.String()
173 type InvalidUTF8Error struct {
177 func (e *InvalidUTF8Error) Error() string {
178 return "json: invalid UTF-8 in string: " + strconv.Quote(e.S)
181 type MarshalerError struct {
186 func (e *MarshalerError) Error() string {
187 return "json: error calling MarshalJSON for type " + e.Type.String() + ": " + e.Err.Error()
190 type interfaceOrPtrValue interface {
195 var hex = "0123456789abcdef"
197 // An encodeState encodes JSON into a bytes.Buffer.
198 type encodeState struct {
199 bytes.Buffer // accumulated output
203 func (e *encodeState) marshal(v interface{}) (err error) {
205 if r := recover(); r != nil {
206 if _, ok := r.(runtime.Error); ok {
212 e.reflectValue(reflect.ValueOf(v))
216 func (e *encodeState) error(err error) {
220 var byteSliceType = reflect.TypeOf([]byte(nil))
222 func isEmptyValue(v reflect.Value) bool {
224 case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
228 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
230 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
232 case reflect.Float32, reflect.Float64:
233 return v.Float() == 0
234 case reflect.Interface, reflect.Ptr:
240 func (e *encodeState) reflectValue(v reflect.Value) {
241 e.reflectValueQuoted(v, false)
244 // reflectValueQuoted writes the value in v to the output.
245 // If quoted is true, the serialization is wrapped in a JSON string.
246 func (e *encodeState) reflectValueQuoted(v reflect.Value, quoted bool) {
248 e.WriteString("null")
252 if j, ok := v.Interface().(Marshaler); ok && (v.Kind() != reflect.Ptr || !v.IsNil()) {
253 b, err := j.MarshalJSON()
255 // copy JSON into buffer, checking validity.
256 err = Compact(&e.Buffer, b)
259 e.error(&MarshalerError{v.Type(), err})
264 writeString := (*encodeState).WriteString
266 writeString = (*encodeState).string
273 writeString(e, "true")
275 writeString(e, "false")
278 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
279 b := strconv.AppendInt(e.scratch[:0], v.Int(), 10)
281 writeString(e, string(b))
285 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
286 b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10)
288 writeString(e, string(b))
292 case reflect.Float32, reflect.Float64:
293 b := strconv.AppendFloat(e.scratch[:0], v.Float(), 'g', -1, v.Type().Bits())
295 writeString(e, string(b))
301 sb, err := Marshal(v.String())
313 for _, ef := range encodeFields(v.Type()) {
314 fieldValue := v.Field(ef.i)
315 if ef.omitEmpty && isEmptyValue(fieldValue) {
325 e.reflectValueQuoted(fieldValue, ef.quoted)
330 if v.Type().Key().Kind() != reflect.String {
331 e.error(&UnsupportedTypeError{v.Type()})
334 e.WriteString("null")
338 var sv stringValues = v.MapKeys()
340 for i, k := range sv {
346 e.reflectValue(v.MapIndex(k))
352 e.WriteString("null")
355 if v.Type().Elem().Kind() == reflect.Uint8 {
356 // Byte slices get special treatment; arrays don't.
360 // for small buffers, using Encode directly is much faster.
361 dst := make([]byte, base64.StdEncoding.EncodedLen(len(s)))
362 base64.StdEncoding.Encode(dst, s)
365 // for large buffers, avoid unnecessary extra temporary
367 enc := base64.NewEncoder(base64.StdEncoding, e)
374 // Slices can be marshalled as nil, but otherwise are handled
380 for i := 0; i < n; i++ {
384 e.reflectValue(v.Index(i))
388 case reflect.Interface, reflect.Ptr:
390 e.WriteString("null")
393 e.reflectValue(v.Elem())
396 e.error(&UnsupportedTypeError{v.Type()})
401 func isValidTag(s string) bool {
405 for _, c := range s {
406 if c != '$' && c != '-' && c != '_' && !unicode.IsLetter(c) && !unicode.IsDigit(c) {
413 // stringValues is a slice of reflect.Value holding *reflect.StringValue.
414 // It implements the methods to sort by string.
415 type stringValues []reflect.Value
417 func (sv stringValues) Len() int { return len(sv) }
418 func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] }
419 func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) }
420 func (sv stringValues) get(i int) string { return sv[i].String() }
422 func (e *encodeState) string(s string) (int, error) {
426 for i := 0; i < len(s); {
427 if b := s[i]; b < utf8.RuneSelf {
428 if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' {
433 e.WriteString(s[start:i])
446 // This encodes bytes < 0x20 except for \n and \r,
447 // as well as < and >. The latter are escaped because they
448 // can lead to security holes when user-controlled strings
449 // are rendered into JSON and served to some browsers.
450 e.WriteString(`\u00`)
451 e.WriteByte(hex[b>>4])
452 e.WriteByte(hex[b&0xF])
458 c, size := utf8.DecodeRuneInString(s[i:])
459 if c == utf8.RuneError && size == 1 {
460 e.error(&InvalidUTF8Error{s})
465 e.WriteString(s[start:])
468 return e.Len() - len0, nil
471 // encodeField contains information about how to encode a field of a
473 type encodeField struct {
474 i int // field index in struct
481 typeCacheLock sync.RWMutex
482 encodeFieldsCache = make(map[reflect.Type][]encodeField)
485 // encodeFields returns a slice of encodeField for a given
487 func encodeFields(t reflect.Type) []encodeField {
488 typeCacheLock.RLock()
489 fs, ok := encodeFieldsCache[t]
490 typeCacheLock.RUnlock()
496 defer typeCacheLock.Unlock()
497 fs, ok = encodeFieldsCache[t]
504 for i := 0; i < n; i++ {
513 tv := f.Tag.Get("json")
518 name, opts := parseTag(tv)
519 if isValidTag(name) {
522 ef.omitEmpty = opts.Contains("omitempty")
523 ef.quoted = opts.Contains("string")
527 encodeFieldsCache[t] = fs