// 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. // The json package implements encoding and decoding of JSON objects as // defined in RFC 4627. package json import ( "os" "bytes" "reflect" "runtime" "sort" "strconv" "utf8" ) // 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. // // Array and slice values encode as JSON arrays. // // Struct values encode as JSON objects. Each struct field becomes // a member of the object. By default the object's key name is the // struct field name converted to lower case. If the struct field // has a tag, that tag will be used as the name instead. // Only exported fields will be encoded. // // Map values encode as JSON objects. // The map's key type must be string; the object keys are used directly // as map keys. // // Pointer values encode as the value pointed to. // 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 } // 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