hjson

package module
v4.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 7, 2023 License: MIT Imports: 12 Imported by: 48

README

hjson-go

Build Status Go Pkg Go Report Card coverage godoc

Hjson Intro

{
  # specify rate in requests/second (because comments are helpful!)
  rate: 1000

  // prefer c-style comments?
  /* feeling old fashioned? */

  # did you notice that rate doesn't need quotes?
  hey: look ma, no quotes for strings either!

  # best of all
  notice: []
  anything: ?

  # yes, commas are optional!
}

The Go implementation of Hjson is based on hjson-js. For other platforms see hjson.github.io.

More documentation can be found at https://pkg.go.dev/github.com/hjson/hjson-go/v4

Install

Instructions for installing a pre-built hjson-cli tool can be found at https://hjson.github.io/users-bin.html

If you instead want to build locally, make sure you have a working Go environment. See the install instructions.

  • In order to use Hjson from your own Go source code, just add an import line like the one here below. Before building your project, run go mod tidy in order to download the Hjson source files. The suffix /v4 is required in the import path, unless you specifically want to use an older major version.
import "github.com/hjson/hjson-go/v4"
  • If you instead want to use the hjson-cli command line tool, run the command here below in your terminal. The executable will be installed into your go/bin folder, make sure that folder is included in your PATH environment variable.
go install github.com/hjson/hjson-go/v4/hjson-cli@latest

Usage as command line tool

usage: hjson-cli [OPTIONS] [INPUT]
hjson can be used to convert JSON from/to Hjson.

hjson will read the given JSON/Hjson input file or read from stdin.

Options:
  -bracesSameLine
      Print braces on the same line.
  -c  Output as JSON.
  -h  Show this screen.
  -indentBy string
      The indent string. (default "  ")
  -j  Output as formatted JSON.
  -omitRootBraces
      Omit braces at the root.
  -preserveKeyOrder
      Preserve key order in objects/maps.
  -quoteAlways
      Always quote string values.
  -v
      Show version.

Sample:

  • run hjson-cli test.json > test.hjson to convert to Hjson
  • run hjson-cli -j test.hjson > test.json to convert to JSON

Usage as a GO library


package main

import (
    "github.com/hjson/hjson-go/v4"
    "fmt"
)

func main() {
    // Now let's look at decoding Hjson data into Go
    // values.
    sampleText := []byte(`
    {
        # specify rate in requests/second
        rate: 1000
        array:
        [
            foo
            bar
        ]
    }`)

    // We need to provide a variable where Hjson
    // can put the decoded data.
    var dat map[string]interface{}

    // Decode with default options and check for errors.
    if err := hjson.Unmarshal(sampleText, &dat); err != nil {
        panic(err)
    }
    // short for:
    // options := hjson.DefaultDecoderOptions()
    // err := hjson.UnmarshalWithOptions(sampleText, &dat, options)
    fmt.Println(dat)

    // In order to use the values in the decoded map,
    // we'll need to cast them to their appropriate type.

    rate := dat["rate"].(float64)
    fmt.Println(rate)

    array := dat["array"].([]interface{})
    str1 := array[0].(string)
    fmt.Println(str1)


    // To encode to Hjson with default options:
    sampleMap := map[string]int{"apple": 5, "lettuce": 7}
    hjson, _ := hjson.Marshal(sampleMap)
    // short for:
    // options := hjson.DefaultOptions()
    // hjson, _ := hjson.MarshalWithOptions(sampleMap, options)
    fmt.Println(string(hjson))
}

Unmarshal to Go structs

If you prefer, you can also unmarshal to Go structs (including structs implementing the json.Unmarshaler interface or the encoding.TextUnmarshaler interface). The Go JSON package is used for this, so the same rules apply. Specifically for the "json" key in struct field tags. For more details about this type of unmarshalling, see the documentation for json.Unmarshal().


package main

import (
    "github.com/hjson/hjson-go/v4"
    "fmt"
)

type Sample struct {
    Rate  int
    Array []string
}

type SampleAlias struct {
    Rett    int      `json:"rate"`
    Ashtray []string `json:"array"`
}

func main() {
    sampleText := []byte(`
    {
        # specify rate in requests/second
        rate: 1000
        array:
        [
            foo
            bar
        ]
    }`)

    // unmarshal
    var sample Sample
    hjson.Unmarshal(sampleText, &sample)

    fmt.Println(sample.Rate)
    fmt.Println(sample.Array)

    // unmarshal using json tags on struct fields
    var sampleAlias SampleAlias
    hjson.Unmarshal(sampleText, &sampleAlias)

    fmt.Println(sampleAlias.Rett)
    fmt.Println(sampleAlias.Ashtray)
}

Comments on struct fields

By using key comment in struct field tags you can specify comments to be written on one or more lines preceding the struct field in the Hjson output. Another way to output comments is to use hjson.Node structs, more on than later.


package main

import (
    "github.com/hjson/hjson-go/v4"
    "fmt"
)

type foo struct {
    A string `json:"x" comment:"First comment"`
    B int32  `comment:"Second comment\nLook ma, new lines"`
    C string
    D int32
}

func main() {
    a := foo{A: "hi!", B: 3, C: "some text", D: 5}
    buf, err := hjson.Marshal(a)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(string(buf))
}

Output:

{
  # First comment
  x: hi!

  # Second comment
  # Look ma, new lines
  B: 3

  C: some text
  D: 5
}

Read and write comments

The only way to read comments from Hjson input is to use a destination variable of type hjson.Node or *hjson.Node. The hjson.Node must be the root destination, it won't work if you create a field of type hjson.Node in some other struct and use that struct as destination. An hjson.Node struct is simply a wrapper for a value and comments stored in an hjson.Comments struct. It also has several convenience functions, for example AtIndex() or SetKey() that can be used when you know that the node contains a value of type []interface{} or *hjson.OrderedMap. All of the elements in []interface{} or *hjson.OrderedMap will be of type *hjson.Node in trees created by hjson.Unmarshal, but the hjson.Node convenience functions unpack the actual values from them.

When hjson.Node or *hjson.Node is used as destination for Hjson unmarshal the output will be a tree of *hjson.Node where all of the values contained in tree nodes will be of these types:

  • nil (no type)
  • float64   (if UseJSONNumber == false)
  • json.Number   (if UseJSONNumber == true)
  • string
  • bool
  • []interface{}
  • *hjson.OrderedMap

These are just the types used by Hjson unmarshal and the convenience functions, you are free to assign any type of values to nodes in your own code.

The comments will contain all whitespace chars too (including line feeds) so that an Hjson document can be read and written without altering the layout. This can be disabled by setting the decoding option WhitespaceAsComments to false.


package main

import (
    "fmt"

    "github.com/hjson/hjson-go/v4"
)

func main() {
    // Now let's look at decoding Hjson data into hjson.Node.
    sampleText := []byte(`
    {
        # specify rate in requests/second
        rate: 1000
        array:
        [
            foo
            bar
        ]
    }`)

    var node hjson.Node
    if err := hjson.Unmarshal(sampleText, &node); err != nil {
        panic(err)
    }

    node.NK("array").Cm.Before = `        # please specify an array
        `

    if _, _, err := node.NKC("subMap").SetKey("subVal", 1); err != nil {
        panic(err)
    }

    outBytes, err := hjson.Marshal(node)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(outBytes))
}

Output:


    {
        # specify rate in requests/second
        rate: 1000
        # please specify an array
        array:
        [
            foo
            bar
        ]
  subMap: {
    subVal: 1
  }
    }

Type ambiguity

Hjson allows quoteless strings. But if a value is a valid number, boolean or null then it will be unmarshalled into that type instead of a string when unmarshalling into interface{}. This can lead to unintended consequences if the creator of an Hjson file meant to write a string but didn't think of that the quoteless string they wrote also was a valid number.

The ambiguity can be avoided by using typed destinations when unmarshalling. A string destination will receive a string even if the quoteless string also was a valid number, boolean or null. Example:


package main

import (
    "github.com/hjson/hjson-go/v4"
    "fmt"
)

type foo struct {
  A string
}

func main() {
    var dest foo
    err := hjson.Unmarshal([]byte(`a: 3`), &dest)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(dest)
}

Output:

{3}

String pointer destinations are treated the same as string destinations, so you cannot set a string pointer to nil by writing null in an Hjson file. Writing null in an Hjson file would result in the string "null" being stored in the destination string pointer.

ElemTyper interface

If a destination type implements hjson.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.

Example implementation for a generic ordered map:


func (o *OrderedMap[T]) ElemType() reflect.Type {
  return reflect.TypeOf((*T)(nil)).Elem()
}

API

godoc

History

see releases

Documentation

Index

Constants

This section is empty.

Variables

View Source
var JSONNumberType = reflect.TypeOf(json.Number(""))

Functions

func Marshal

func Marshal(v interface{}) ([]byte, error)

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

func Unmarshal(data []byte, v interface{}) error

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

func (c *Node) Append(value interface{}) error

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

func (c *Node) AtIndex(index int) (string, interface{}, error)

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

func (c *Node) AtKey(key string) (interface{}, bool, error)

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

func (c *Node) DeleteIndex(index int) (string, interface{}, error)

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

func (c *Node) DeleteKey(key string) (interface{}, bool, error)

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

func (c *Node) Insert(index int, key string, value interface{}) (interface{}, bool, error)

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

func (c *Node) Len() int

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

func (c Node) MarshalJSON() ([]byte, error)

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

func (c *Node) NI(index int) *Node

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

func (c *Node) NK(key string) *Node

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

func (c *Node) NKC(key string) *Node

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

func (c *Node) SetIndex(index int, value interface{}) (string, interface{}, error)

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

func (c *Node) SetKey(key string, value interface{}) (interface{}, bool, error)

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

func (c *Node) UnmarshalJSON(b []byte) error

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

type OrderedMap struct {
	Keys []string
	Map  map[string]interface{}
}

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().

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL