hjson

package module
v4.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2022 License: MIT Imports: 12 Imported by: 86

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

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/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.
  -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.


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.Error(err)
    }

    fmt.Println(string(buf))
}

Output:

{
  # First comment
  x: hi!

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

  C: some text
  D: 5
}

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.

Internally the Hjson input is converted to JSON, which is then used as input to the function json.Unmarshal().

For more details about the output from this function, see the documentation for json.Unmarshal().

Types

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
}

DecoderOptions defines options for decoding Hjson.

func DefaultDecoderOptions

func DefaultDecoderOptions() DecoderOptions

DefaultDecoderOptions returns the default decoding options.

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
}

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 = ""

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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