encode.go 8.89 KB
Newer Older
1 2 3 4
// Copyright 2010 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5 6
// Package json implements encoding and decoding of JSON objects as defined in
// RFC 4627.
7 8 9 10
package json

import (
	"bytes"
11 12
	"encoding/base64"
	"os"
13 14 15 16
	"reflect"
	"runtime"
	"sort"
	"strconv"
Russ Cox's avatar
Russ Cox committed
17
	"unicode"
Russ Cox's avatar
Russ Cox committed
18
	"utf8"
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
)

// Marshal returns the JSON encoding of v.
//
// Marshal traverses the value v recursively.
// If an encountered value implements the Marshaler interface,
// Marshal calls its MarshalJSON method to produce JSON.
//
// Otherwise, Marshal uses the following type-dependent default encodings:
//
// Boolean values encode as JSON booleans.
//
// Floating point and integer values encode as JSON numbers.
//
// String values encode as JSON strings, with each invalid UTF-8 sequence
// replaced by the encoding of the Unicode replacement character U+FFFD.
//
36 37
// Array and slice values encode as JSON arrays, except that
// []byte encodes as a base64-encoded string.
38
//
39 40
// Struct values encode as JSON objects.  Each exported struct field
// becomes a member of the object.  By default the object's key string
41 42 43 44 45
// is the struct field name.  If the struct field's tag has a "json"
// key with a value that is a non-empty string consisting of only
// Unicode letters, digits, dollar signs, hyphens, and underscores,
// that value will be used as the object key.  For example, the field
// tag `json:"myName"` says to use "myName" as the object key.
46 47 48 49 50
//
// Map values encode as JSON objects.
// The map's key type must be string; the object keys are used directly
// as map keys.
//
51
// Pointer values encode as the value pointed to.
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
// A nil pointer encodes as the null JSON object.
//
// Interface values encode as the value contained in the interface.
// A nil interface value encodes as the null JSON object.
//
// Channel, complex, and function values cannot be encoded in JSON.
// Attempting to encode such a value causes Marshal to return
// an InvalidTypeError.
//
// JSON cannot represent cyclic data structures and Marshal does not
// handle them.  Passing cyclic structures to Marshal will result in
// an infinite recursion.
//
func Marshal(v interface{}) ([]byte, os.Error) {
	e := &encodeState{}
	err := e.marshal(v)
	if err != nil {
		return nil, err
	}
	return e.Bytes(), nil
}

// MarshalIndent is like Marshal but applies Indent to format the output.
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, os.Error) {
	b, err := Marshal(v)
	if err != nil {
		return nil, err
	}
	var buf bytes.Buffer
	err = Indent(&buf, b, prefix, indent)
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

Micah Stetson's avatar
Micah Stetson committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
// MarshalForHTML is like Marshal but applies HTMLEscape to the output.
func MarshalForHTML(v interface{}) ([]byte, os.Error) {
	b, err := Marshal(v)
	if err != nil {
		return nil, err
	}
	var buf bytes.Buffer
	HTMLEscape(&buf, b)
	return buf.Bytes(), nil
}

// HTMLEscape appends to dst the JSON-encoded src with <, >, and &
// characters inside string literals changed to \u003c, \u003e, \u0026
// so that the JSON will be safe to embed inside HTML <script> tags.
// For historical reasons, web browsers don't honor standard HTML
// escaping within <script> tags, so an alternative JSON encoding must
// be used.
func HTMLEscape(dst *bytes.Buffer, src []byte) {
	// < > & can only appear in string literals,
	// so just scan the string one byte at a time.
	start := 0
	for i, c := range src {
		if c == '<' || c == '>' || c == '&' {
			if start < i {
				dst.Write(src[start:i])
			}
			dst.WriteString(`\u00`)
			dst.WriteByte(hex[c>>4])
			dst.WriteByte(hex[c&0xF])
			start = i + 1
		}
	}
	if start < len(src) {
		dst.Write(src[start:])
	}
}

125 126 127 128 129 130 131 132 133 134 135 136 137 138
// Marshaler is the interface implemented by objects that
// can marshal themselves into valid JSON.
type Marshaler interface {
	MarshalJSON() ([]byte, os.Error)
}

type UnsupportedTypeError struct {
	Type reflect.Type
}

func (e *UnsupportedTypeError) String() string {
	return "json: unsupported type: " + e.Type.String()
}

Russ Cox's avatar
Russ Cox committed
139 140 141 142 143 144 145 146
type InvalidUTF8Error struct {
	S string
}

func (e *InvalidUTF8Error) String() string {
	return "json: invalid UTF-8 in string: " + strconv.Quote(e.S)
}

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
type MarshalerError struct {
	Type  reflect.Type
	Error os.Error
}

func (e *MarshalerError) String() string {
	return "json: error calling MarshalJSON for type " + e.Type.String() + ": " + e.Error.String()
}

type interfaceOrPtrValue interface {
	IsNil() bool
	Elem() reflect.Value
}

var hex = "0123456789abcdef"

// An encodeState encodes JSON into a bytes.Buffer.
type encodeState struct {
	bytes.Buffer // accumulated output
}

func (e *encodeState) marshal(v interface{}) (err os.Error) {
	defer func() {
		if r := recover(); r != nil {
			if _, ok := r.(runtime.Error); ok {
				panic(r)
			}
			err = r.(os.Error)
		}
	}()
Russ Cox's avatar
Russ Cox committed
177
	e.reflectValue(reflect.ValueOf(v))
178 179 180 181 182 183 184
	return nil
}

func (e *encodeState) error(err os.Error) {
	panic(err)
}

Russ Cox's avatar
Russ Cox committed
185
var byteSliceType = reflect.TypeOf([]byte(nil))
186

187
func (e *encodeState) reflectValue(v reflect.Value) {
188
	if !v.IsValid() {
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
		e.WriteString("null")
		return
	}

	if j, ok := v.Interface().(Marshaler); ok {
		b, err := j.MarshalJSON()
		if err == nil {
			// copy JSON into buffer, checking validity.
			err = Compact(&e.Buffer, b)
		}
		if err != nil {
			e.error(&MarshalerError{v.Type(), err})
		}
		return
	}

205 206 207
	switch v.Kind() {
	case reflect.Bool:
		x := v.Bool()
208 209 210 211 212 213
		if x {
			e.WriteString("true")
		} else {
			e.WriteString("false")
		}

214 215
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		e.WriteString(strconv.Itoa64(v.Int()))
216

217 218
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		e.WriteString(strconv.Uitoa64(v.Uint()))
219

220 221
	case reflect.Float32, reflect.Float64:
		e.WriteString(strconv.FtoaN(v.Float(), 'g', -1, v.Type().Bits()))
222

223 224
	case reflect.String:
		e.string(v.String())
225

226
	case reflect.Struct:
227
		e.WriteByte('{')
228
		t := v.Type()
229
		n := v.NumField()
230
		first := true
231
		for i := 0; i < n; i++ {
232 233 234 235 236 237 238
			f := t.Field(i)
			if f.PkgPath != "" {
				continue
			}
			if first {
				first = false
			} else {
239 240
				e.WriteByte(',')
			}
241 242
			if tag := f.Tag.Get("json"); tag != "" && isValidTag(tag) {
				e.string(tag)
243
			} else {
244
				e.string(f.Name)
245 246 247 248 249 250
			}
			e.WriteByte(':')
			e.reflectValue(v.Field(i))
		}
		e.WriteByte('}')

251 252
	case reflect.Map:
		if v.Type().Key().Kind() != reflect.String {
253 254 255 256 257 258 259
			e.error(&UnsupportedTypeError{v.Type()})
		}
		if v.IsNil() {
			e.WriteString("null")
			break
		}
		e.WriteByte('{')
260
		var sv stringValues = v.MapKeys()
261 262 263 264 265
		sort.Sort(sv)
		for i, k := range sv {
			if i > 0 {
				e.WriteByte(',')
			}
266
			e.string(k.String())
267
			e.WriteByte(':')
268
			e.reflectValue(v.MapIndex(k))
269 270 271
		}
		e.WriteByte('}')

272
	case reflect.Array, reflect.Slice:
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
		if v.Type() == byteSliceType {
			e.WriteByte('"')
			s := v.Interface().([]byte)
			if len(s) < 1024 {
				// for small buffers, using Encode directly is much faster.
				dst := make([]byte, base64.StdEncoding.EncodedLen(len(s)))
				base64.StdEncoding.Encode(dst, s)
				e.Write(dst)
			} else {
				// for large buffers, avoid unnecessary extra temporary
				// buffer space.
				enc := base64.NewEncoder(base64.StdEncoding, e)
				enc.Write(s)
				enc.Close()
			}
			e.WriteByte('"')
			break
		}
291 292 293 294 295 296
		e.WriteByte('[')
		n := v.Len()
		for i := 0; i < n; i++ {
			if i > 0 {
				e.WriteByte(',')
			}
297
			e.reflectValue(v.Index(i))
298 299 300
		}
		e.WriteByte(']')

301
	case reflect.Interface, reflect.Ptr:
302 303 304 305 306 307 308 309 310 311 312 313
		if v.IsNil() {
			e.WriteString("null")
			return
		}
		e.reflectValue(v.Elem())

	default:
		e.error(&UnsupportedTypeError{v.Type()})
	}
	return
}

Russ Cox's avatar
Russ Cox committed
314 315 316 317 318
func isValidTag(s string) bool {
	if s == "" {
		return false
	}
	for _, c := range s {
319
		if c != '$' && c != '-' && c != '_' && !unicode.IsLetter(c) && !unicode.IsDigit(c) {
Russ Cox's avatar
Russ Cox committed
320 321 322 323 324 325
			return false
		}
	}
	return true
}

326 327 328 329 330 331 332
// stringValues is a slice of reflect.Value holding *reflect.StringValue.
// It implements the methods to sort by string.
type stringValues []reflect.Value

func (sv stringValues) Len() int           { return len(sv) }
func (sv stringValues) Swap(i, j int)      { sv[i], sv[j] = sv[j], sv[i] }
func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) }
333
func (sv stringValues) get(i int) string   { return sv[i].String() }
334 335 336

func (e *encodeState) string(s string) {
	e.WriteByte('"')
Russ Cox's avatar
Russ Cox committed
337 338 339 340 341 342 343 344 345 346
	start := 0
	for i := 0; i < len(s); {
		if b := s[i]; b < utf8.RuneSelf {
			if 0x20 <= b && b != '\\' && b != '"' {
				i++
				continue
			}
			if start < i {
				e.WriteString(s[start:i])
			}
347 348
			switch b {
			case '\\', '"':
Russ Cox's avatar
Russ Cox committed
349 350
				e.WriteByte('\\')
				e.WriteByte(b)
351 352 353 354 355 356 357
			case '\n':
				e.WriteByte('\\')
				e.WriteByte('n')
			case '\r':
				e.WriteByte('\\')
				e.WriteByte('r')
			default:
Russ Cox's avatar
Russ Cox committed
358 359 360 361 362 363 364 365 366 367 368
				e.WriteString(`\u00`)
				e.WriteByte(hex[b>>4])
				e.WriteByte(hex[b&0xF])
			}
			i++
			start = i
			continue
		}
		c, size := utf8.DecodeRuneInString(s[i:])
		if c == utf8.RuneError && size == 1 {
			e.error(&InvalidUTF8Error{s})
369
		}
Russ Cox's avatar
Russ Cox committed
370 371 372 373
		i += size
	}
	if start < len(s) {
		e.WriteString(s[start:])
374 375 376
	}
	e.WriteByte('"')
}