Documentation ¶
Index ¶
- Variables
- func Marshal(v interface{}) ([]byte, error)
- func MarshalWithOptions(v interface{}, options EncoderOptions) ([]byte, error)
- func Unmarshal(data []byte, v interface{}) error
- func UnmarshalWithOptions(data []byte, v interface{}, options DecoderOptions) error
- type Comments
- type DecoderOptions
- type ElemTyper
- type EncoderOptions
- type KeyValue
- type Node
- func (c *Node) Append(value interface{}) error
- func (c *Node) AtIndex(index int) (string, interface{}, error)
- func (c *Node) AtKey(key string) (interface{}, bool, error)
- func (c *Node) DeleteIndex(index int) (string, interface{}, error)
- func (c *Node) DeleteKey(key string) (interface{}, bool, error)
- func (c *Node) Insert(index int, key string, value interface{}) (interface{}, bool, error)
- func (c *Node) Len() int
- func (c Node) MarshalJSON() ([]byte, error)
- func (c *Node) NI(index int) *Node
- func (c *Node) NK(key string) *Node
- func (c *Node) NKC(key string) *Node
- func (c *Node) SetIndex(index int, value interface{}) (string, interface{}, error)
- func (c *Node) SetKey(key string, value interface{}) (interface{}, bool, error)
- func (c *Node) UnmarshalJSON(b []byte) error
- type OrderedMap
- func (c *OrderedMap) AtIndex(index int) interface{}
- func (c *OrderedMap) AtKey(key string) (interface{}, bool)
- func (c *OrderedMap) DeleteIndex(index int) (string, interface{})
- func (c *OrderedMap) DeleteKey(key string) (interface{}, bool)
- func (c *OrderedMap) Insert(index int, key string, value interface{}) (interface{}, bool)
- func (c *OrderedMap) Len() int
- func (c *OrderedMap) MarshalJSON() ([]byte, error)
- func (c *OrderedMap) Set(key string, value interface{}) (interface{}, bool)
- func (c *OrderedMap) UnmarshalJSON(b []byte) error
Constants ¶
This section is empty.
Variables ¶
var JSONNumberType = reflect.TypeOf(json.Number(""))
Functions ¶
func Marshal ¶
Marshal returns the Hjson encoding of v using default options.
See MarshalWithOptions.
func MarshalWithOptions ¶
func MarshalWithOptions(v interface{}, options EncoderOptions) ([]byte, error)
MarshalWithOptions returns the Hjson encoding of v.
The value v is traversed recursively.
Boolean values are written as true or false.
Floating point, integer, and json.Number values are written as numbers (with decimals only if needed, using . as decimals separator).
String values encode as Hjson strings (quoteless, multiline or JSON).
Array and slice values encode as arrays, surrounded by []. Unlike json.Marshal, hjson.Marshal will encode a nil-slice as [] instead of null.
Map values encode as objects, surrounded by {}. The map's key type must be possible to print to a string using fmt.Sprintf("%v", key), or implement encoding.TextMarshaler. The map keys are sorted alphabetically and used as object keys. Unlike json.Marshal, hjson.Marshal will encode a nil-map as {} instead of null.
Struct values also encode as objects, surrounded by {}. Only the exported fields are encoded to Hjson. The fields will appear in the same order as in the struct.
The encoding of each struct field can be customized by the format string stored under the "json" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma and "omitempty". The name may be empty in order to specify "omitempty" without overriding the default field name.
The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.
As a special case, if the field tag is "-", the field is always omitted. Note that a field with name "-" can still be generated using the tag "-,".
Comments can be set on struct fields using the "comment" key in the struct field's tag. The comment will be written on the line before the field key, prefixed with #. Or possible several lines prefixed by #, if there are line breaks (\n) in the comment text.
If both the "json" and the "comment" tag keys are used on a struct field they should be separated by whitespace.
Examples of struct field tags and their meanings:
// Field appears in Hjson as key "myName". Field int `json:"myName"` // Field appears in Hjson as key "myName" and the field is omitted from // the object if its value is empty, as defined above. Field int `json:"myName,omitempty"` // Field appears in Hjson as key "Field" (the default), but the field is // skipped if empty. Note the leading comma. Field int `json:",omitempty"` // Field is ignored by this package. Field int `json:"-"` // Field appears in Hjson as key "-". Field int `json:"-,"` // Field appears in Hjson preceded by a line just containing `# A comment.` Field int `comment:"A comment."` // Field appears in Hjson as key "myName" preceded by a line just // containing `# A comment.` Field int `json:"myName" comment:"A comment."`
Anonymous struct fields are usually marshaled as if their inner exported fields were fields in the outer struct, subject to the usual Go visibility rules amended as described in the next paragraph. An anonymous struct field with a name given in its JSON tag is treated as having that name, rather than being anonymous. An anonymous struct field of interface type is treated the same as having that type as its name, rather than being anonymous.
The Go visibility rules for struct fields are amended for JSON when deciding which field to marshal or unmarshal. If there are multiple fields at the same level, and that level is the least nested (and would therefore be the nesting level selected by the usual Go rules), the following extra rules apply:
1) Of those fields, if any are JSON-tagged, only tagged fields are considered, even if there are multiple untagged fields that would otherwise conflict.
2) If there is exactly one field (tagged or not according to the first rule), that is selected.
3) Otherwise there are multiple fields, and all are ignored; no error occurs.
Pointer values encode as the value pointed to. A nil pointer encodes as the null JSON value.
Interface values encode as the value contained in the interface. A nil interface value encodes as the null JSON value.
If an encountered value implements the json.Marshaler interface then the function MarshalJSON() is called on it. The JSON is then converted to Hjson using the current indentation and options given in the call to json.Marshal().
If an encountered value implements the encoding.TextMarshaler interface but not the json.Marshaler interface, then the function MarshalText() is called on it to get a text.
Channel, complex, and function values cannot be encoded in Hjson, will result in an error.
Hjson cannot represent cyclic data structures and Marshal does not handle them. Passing cyclic structures to Marshal will result in an error.
func Unmarshal ¶
Unmarshal parses the Hjson-encoded data using default options and stores the result in the value pointed to by v.
See UnmarshalWithOptions.
func UnmarshalWithOptions ¶
func UnmarshalWithOptions(data []byte, v interface{}, options DecoderOptions) error
UnmarshalWithOptions parses the Hjson-encoded data and stores the result in the value pointed to by v.
The Hjson input is internally converted to JSON, which is then used as input to the function json.Unmarshal(). Unless the input argument v is of any of these types:
*hjson.OrderedMap **hjson.OrderedMap *hjson.Node **hjson.Node
Comments can be read from the Hjson-encoded data, but only if the input argument v is of type *hjson.Node or **hjson.Node.
For more details about the output from this function, see the documentation for json.Unmarshal().
Types ¶
type Comments ¶ added in v4.3.0
type Comments struct { // Comment/whitespace on line(s) before the value, and before the value on // the same line. If not empty, is expected to end with a line feed + // indentation for the value. Before string // Comment/whitespace between the key and this value, if this value is an // element in a map/object. Key string // Comment/whitespace after (but still on the same line as) the leading // bracket ({ or [) for this value, if this value is a slice/array or // map/object. Is not expected to contain any line feed. InsideFirst string // Comment/whitespace from the beginning of the first line after all child // values belonging to this value, until the closing bracket (} or ]), if // this value is a slice/array or map/object. If not empty, is expected to // end with a line feed + indentation for the closing bracket. InsideLast string // Comment/whitespace after (but still on the same line as) the value. Is not // expected to contain any line feed. hjson.Unmarshal() will try to assign // comments/whitespace from lines between values to `Before` on the value // after those lines, or to `InsideLast` on the slice/map if the lines // containing comments appear after the last element inside a slice/map. After string }
type DecoderOptions ¶
type DecoderOptions struct { // UseJSONNumber causes the Decoder to unmarshal a number into an interface{} as a // json.Number instead of as a float64. UseJSONNumber bool // DisallowUnknownFields causes an error to be returned when the destination // is a struct and the input contains object keys which do not match any // non-ignored, exported fields in the destination. DisallowUnknownFields bool // DisallowDuplicateKeys causes an error to be returned if an object (map) in // the Hjson input contains duplicate keys. If DisallowDuplicateKeys is set // to false, later values will silently overwrite previous values for the // same key. DisallowDuplicateKeys bool // WhitespaceAsComments only has any effect when an hjson.Node struct (or // an *hjson.Node pointer) is used as target for Unmarshal. If // WhitespaceAsComments is set to true, all whitespace and comments are stored // in the Node structs so that linefeeds and custom indentation is kept. If // WhitespaceAsComments instead is set to false, only actual comments are // stored as comments in Node structs. WhitespaceAsComments bool }
DecoderOptions defines options for decoding Hjson.
func DefaultDecoderOptions ¶
func DefaultDecoderOptions() DecoderOptions
DefaultDecoderOptions returns the default decoding options.
type ElemTyper ¶ added in v4.2.0
type ElemTyper interface { // Returns the desired type of any elements. If ElemType() is implemented // using a pointer receiver it must be possible to call with nil as receiver. ElemType() reflect.Type }
If a destination type implements ElemTyper, Unmarshal() will call ElemType() on the destination when unmarshalling an array or an object, to see if any array element or leaf node should be of type string even if it can be treated as a number, boolean or null. This is most useful if the destination also implements the json.Unmarshaler interface, because then there is no other way for Unmarshal() to know the type of the elements on the destination. If a destination implements ElemTyper all of its elements must be of the same type.
type EncoderOptions ¶
type EncoderOptions struct { // End of line, should be either \n or \r\n Eol string // Place braces on the same line BracesSameLine bool // Emit braces for the root object EmitRootBraces bool // Always place string in quotes QuoteAlways bool // Place string in quotes if it could otherwise be a number, boolean or null QuoteAmbiguousStrings bool // Indent string IndentBy string // Base indentation string BaseIndentation string // Write comments, if any are found in hjson.Node structs or as tags on // other structs. Comments bool }
EncoderOptions defines options for encoding to Hjson.
func DefaultOptions ¶
func DefaultOptions() EncoderOptions
DefaultOptions returns the default encoding options. Eol = "\n" BracesSameLine = true EmitRootBraces = true QuoteAlways = false QuoteAmbiguousStrings = true IndentBy = " " BaseIndentation = "" Comments = true
type KeyValue ¶ added in v4.3.0
type KeyValue struct { Key string Value interface{} }
KeyValue is only used as input to NewOrderedMapFromSlice().
type Node ¶ added in v4.3.0
type Node struct { Value interface{} Cm Comments }
Node must be used as destination for Unmarshal() or UnmarshalWithOptions() whenever comments should be read from the input. The struct is simply a wrapper for the actual values and a helper struct containing any comments. The Value in the destination Node will be overwritten in the call to Unmarshal() or UnmarshalWithOptions(), i.e. node trees are not merged. After the unmarshal, Node.Value will contain any of these types:
nil (no type) float64 (if UseJSONNumber == false) json.Number (if UseJSONNumber == true) string bool []interface{} *hjson.OrderedMap
All elements in an []interface{} or *hjson.OrderedMap will be of the type *hjson.Node, so that they can contain comments.
This example shows unmarshalling input with comments, changing the value on a single key (the input is assumed to have an object/map as root) and then marshalling the node tree again, including comments and with preserved key order in the object/map.
var node hjson.Node err := hjson.Unmarshal(input, &node) if err != nil { return err } _, err = node.SetKey("setting1", 3) if err != nil { return err } output, err := hjson.Marshal(node) if err != nil { return err }
func (*Node) Append ¶ added in v4.3.0
Append adds the input value to the end of the []interface{} wrapped by this Node. If this Node contains nil without a type, an empty []interface{} is first created. If this Node contains a value of any other type, an error is returned.
func (*Node) AtIndex ¶ added in v4.3.0
AtIndex returns the key (if any) and value (unwrapped from its Node) found at the specified index, if this Node contains a value of type *hjson.OrderedMap or []interface{}. Returns an error for unexpected types. Panics if index < 0 or index >= Len().
func (*Node) AtKey ¶ added in v4.3.0
AtKey returns the value (unwrapped from its Node) found for the specified key, if this Node contains a value of type *hjson.OrderedMap. An error is returned for unexpected types. The second returned value is true if the key was found, false otherwise.
func (*Node) DeleteIndex ¶ added in v4.3.0
DeleteIndex deletes the value or key/value pair found at the specified index, if this Node contains a value of type *hjson.OrderedMap or []interface{}. Returns an error for unexpected types. Panics if index < 0 or index >= c.Len(). Returns the deleted key (if any) and value.
func (*Node) DeleteKey ¶ added in v4.3.0
DeleteKey deletes the key/value pair with the specified key, if found and if this Node contains a value of type *hjson.OrderedMap. Returns an error for unexpected types. Returns the deleted value and true if the key was found, nil and false otherwise.
func (*Node) Insert ¶ added in v4.3.0
Insert inserts a new key/value pair at the specified index, if this Node contains a value of type *hjson.OrderedMap or []interface{}. Returns an error for unexpected types. Panics if index < 0 or index > c.Len(). If the key already exists in the OrderedMap, the new value is set but the position of the key is not changed. Otherwise the value to insert is wrapped in a new Node. If this Node contains []interface{}, the key is ignored. Returns the old value and true if the key already exists in the/ OrderedMap, nil and false otherwise.
func (*Node) Len ¶ added in v4.3.0
Len returns the length of the value wrapped by this Node, if the value is of type *hjson.OrderedMap, []interface{} or string. Otherwise 0 is returned.
func (Node) MarshalJSON ¶ added in v4.3.0
MarshalJSON is an implementation of the json.Marshaler interface, enabling hjson.Node trees to be used as input for json.Marshal().
func (*Node) NI ¶ added in v4.3.0
NI is an acronym formed from "get Node pointer by Index". Returns the *Node element found at the specified index, if this Node contains a value of type *hjson.OrderedMap or []interface{}. Returns nil otherwise. Panics if index < 0 or index >= Len(). Does not create or alter any value.
func (*Node) NK ¶ added in v4.3.0
NK is an acronym formed from "get Node pointer by Key". Returns the *Node element found for the specified key, if this Node contains a value of type *hjson.OrderedMap. Returns nil otherwise. Does not create or alter anything.
func (*Node) NKC ¶ added in v4.3.0
NKC is an acronym formed from "get Node pointer by Key, Create if not found". Returns the *Node element found for the specified key, if this Node contains a value of type *hjson.OrderedMap. If this Node contains nil without a type, an empty *hjson.OrderedMap is first created. If this Node contains a value of any other type or if the element idendified by the specified key is not of type *Node, an error is returned. If the key cannot be found in the OrderedMap, a new Node is created for the specified key. Example usage:
var node hjson.Node node.NKC("rootKey1").NKC("subKey1").SetKey("valKey1", "my value")
func (*Node) SetIndex ¶ added in v4.3.0
SetIndex assigns the specified value to the child Node found at the specified index, if this Node contains a value of type *hjson.OrderedMap or []interface{}. Returns an error for unexpected types. Returns the key (if any) and value previously found at the specified index. Panics if index < 0 or index >= Len().
func (*Node) SetKey ¶ added in v4.3.0
SetKey assigns the specified value to the child Node identified by the specified key, if this Node contains a value of the type *hjson.OrderedMap. If this Node contains nil without a type, an empty *hjson.OrderedMap is first created. If this Node contains a value of any other type an error is returned. If the key cannot be found in the OrderedMap, a new Node is created, wrapping the specified value, and appended to the end of the OrderedMap. Returns the old value and true if the key already existed in the OrderedMap, nil and false otherwise.
func (*Node) UnmarshalJSON ¶ added in v4.3.0
UnmarshalJSON is an implementation of the json.Unmarshaler interface, enabling hjson.Node to be used as destination for json.Unmarshal().
type OrderedMap ¶ added in v4.3.0
OrderedMap wraps a map and a slice containing all of the keys from the map, so that the order of the keys can be specified. The Keys slice can be sorted or rearranged like any other slice, but do not add or remove keys manually on it. Use OrderedMap.Insert(), OrderedMap.Set(), OrderedMap.DeleteIndex() or OrderedMap.DeleteKey() instead.
Example of how to iterate through the elements of an OrderedMap in order:
for _, key := range om.Keys { fmt.Printf("%v\n", om.Map[key]) }
Always use the functions Insert() or Set() instead of setting values directly on OrderedMap.Map, because any new keys must also be added to OrderedMap.Keys. Otherwise those keys will be ignored when iterating through the elements of the OrderedMap in order, as for example happens in the function hjson.Marshal().
func NewOrderedMap ¶ added in v4.3.0
func NewOrderedMap() *OrderedMap
NewOrderedMap returns a pointer to a new OrderedMap. An OrderedMap should always be passed by reference, never by value. If an OrderedMap is passed by value then appending new keys won't affect all of the copies of the OrderedMap.
func NewOrderedMapFromSlice ¶ added in v4.3.0
func NewOrderedMapFromSlice(args []KeyValue) *OrderedMap
NewOrderedMapFromSlice is like NewOrderedMap but with initial values. Example:
om := NewOrderedMapFromSlice([]KeyValue{ {"B", "first"}, {"A", "second"}, })
func (*OrderedMap) AtIndex ¶ added in v4.3.0
func (c *OrderedMap) AtIndex(index int) interface{}
AtIndex returns the value found at the specified index. Panics if index < 0 or index >= c.Len().
func (*OrderedMap) AtKey ¶ added in v4.3.0
func (c *OrderedMap) AtKey(key string) (interface{}, bool)
AtKey returns the value found for the specified key, and true if the value was found. Returns nil and false if the value was not found.
func (*OrderedMap) DeleteIndex ¶ added in v4.3.0
func (c *OrderedMap) DeleteIndex(index int) (string, interface{})
DeleteIndex deletes the key/value pair found at the specified index. Returns the deleted key and value. Panics if index < 0 or index >= c.Len().
func (*OrderedMap) DeleteKey ¶ added in v4.3.0
func (c *OrderedMap) DeleteKey(key string) (interface{}, bool)
DeleteKey deletes the key/value pair with the specified key, if found. Returns the deleted value and true if the key was found, nil and false otherwise.
func (*OrderedMap) Insert ¶ added in v4.3.0
func (c *OrderedMap) Insert(index int, key string, value interface{}) (interface{}, bool)
Insert inserts a new key/value pair at the specified index. Panics if index < 0 or index > c.Len(). If the key already exists in the OrderedMap, the new value is set but the position of the key is not changed. Returns the old value and true if the key already exists in the OrderedMap, nil and false otherwise.
func (*OrderedMap) Len ¶ added in v4.3.0
func (c *OrderedMap) Len() int
Len returns the number of values contained in the OrderedMap.
func (*OrderedMap) MarshalJSON ¶ added in v4.3.0
func (c *OrderedMap) MarshalJSON() ([]byte, error)
MarshalJSON is an implementation of the json.Marshaler interface, enabling hjson.OrderedMap to be used as input for json.Marshal().
func (*OrderedMap) Set ¶ added in v4.3.0
func (c *OrderedMap) Set(key string, value interface{}) (interface{}, bool)
Set sets the specified value for the specified key. If the key does not already exist in the OrderedMap it is appended to the end of the OrderedMap. If the key already exists in the OrderedMap, the new value is set but the position of the key is not changed. Returns the old value and true if the key already exists in the OrderedMap, nil and false otherwise.
func (*OrderedMap) UnmarshalJSON ¶ added in v4.3.0
func (c *OrderedMap) UnmarshalJSON(b []byte) error
UnmarshalJSON is an implementation of the json.Unmarshaler interface, enabling hjson.OrderedMap to be used as destination for json.Unmarshal().