{"id":13411073,"url":"https://github.com/hjson/hjson-go","last_synced_at":"2025-04-12T21:28:49.164Z","repository":{"id":41106936,"uuid":"65054088","full_name":"hjson/hjson-go","owner":"hjson","description":"Hjson for Go","archived":false,"fork":false,"pushed_at":"2024-04-18T06:50:47.000Z","size":208,"stargazers_count":336,"open_issues_count":5,"forks_count":43,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-04-12T11:57:15.494Z","etag":null,"topics":["go","hjson"],"latest_commit_sha":null,"homepage":"https://hjson.github.io/","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hjson.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-08-05T22:59:18.000Z","updated_at":"2025-03-09T17:04:29.000Z","dependencies_parsed_at":"2023-01-27T19:15:23.032Z","dependency_job_id":"5cd3a3fb-dadc-493f-b812-065f07cf8436","html_url":"https://github.com/hjson/hjson-go","commit_stats":{"total_commits":67,"total_committers":15,"mean_commits":4.466666666666667,"dds":0.582089552238806,"last_synced_commit":"5b236b532097d505bc8d1a73ee93d284490f27ae"},"previous_names":["laktak/hjson-go"],"tags_count":19,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hjson%2Fhjson-go","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hjson%2Fhjson-go/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hjson%2Fhjson-go/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hjson%2Fhjson-go/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hjson","download_url":"https://codeload.github.com/hjson/hjson-go/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248634039,"owners_count":21136967,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["go","hjson"],"created_at":"2024-07-30T20:01:11.224Z","updated_at":"2025-04-12T21:28:49.134Z","avatar_url":"https://github.com/hjson.png","language":"Go","readme":"# hjson-go\n\n[![Build Status](https://github.com/hjson/hjson-go/workflows/test/badge.svg)](https://github.com/hjson/hjson-go/actions)\n[![Go Pkg](https://img.shields.io/github/release/hjson/hjson-go.svg?style=flat-square\u0026label=go-pkg)](https://github.com/hjson/hjson-go/releases)\n[![Go Report Card](https://goreportcard.com/badge/github.com/hjson/hjson-go?style=flat-square)](https://goreportcard.com/report/github.com/hjson/hjson-go)\n[![coverage](https://img.shields.io/badge/coverage-ok-brightgreen.svg?style=flat-square)](https://gocover.io/github.com/hjson/hjson-go/)\n[![godoc](https://img.shields.io/badge/godoc-reference-blue.svg?style=flat-square)](https://godoc.org/github.com/hjson/hjson-go/v4)\n\n![Hjson Intro](https://hjson.github.io/hjson1.gif)\n\n```\n{\n  # specify rate in requests/second (because comments are helpful!)\n  rate: 1000\n\n  // prefer c-style comments?\n  /* feeling old fashioned? */\n\n  # did you notice that rate doesn't need quotes?\n  hey: look ma, no quotes for strings either!\n\n  # best of all\n  notice: []\n  anything: ?\n\n  # yes, commas are optional!\n}\n```\n\nThe Go implementation of Hjson is based on [hjson-js](https://github.com/hjson/hjson-js). For other platforms see [hjson.github.io](https://hjson.github.io).\n\nMore documentation can be found at https://pkg.go.dev/github.com/hjson/hjson-go/v4\n\n# Install\n\nInstructions for installing a pre-built **hjson-cli** tool can be found at https://hjson.github.io/users-bin.html\n\nIf you instead want to build locally, make sure you have a working Go environment. See the [install instructions](https://golang.org/doc/install.html).\n\n- 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.\n```go\nimport \"github.com/hjson/hjson-go/v4\"\n```\n- 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.\n```bash\ngo install github.com/hjson/hjson-go/v4/hjson-cli@latest\n```\n# Usage as command line tool\n```\nusage: hjson-cli [OPTIONS] [INPUT]\nhjson can be used to convert JSON from/to Hjson.\n\nhjson will read the given JSON/Hjson input file or read from stdin.\n\nOptions:\n  -bracesSameLine\n      Print braces on the same line.\n  -c  Output as JSON.\n  -h  Show this screen.\n  -indentBy string\n      The indent string. (default \"  \")\n  -j  Output as formatted JSON.\n  -omitRootBraces\n      Omit braces at the root.\n  -preserveKeyOrder\n      Preserve key order in objects/maps.\n  -quoteAlways\n      Always quote string values.\n  -v\n      Show version.\n```\n\nSample:\n- run `hjson-cli test.json \u003e test.hjson` to convert to Hjson\n- run `hjson-cli -j test.hjson \u003e test.json` to convert to JSON\n\n# Usage as a GO library\n\n```go\n\npackage main\n\nimport (\n    \"github.com/hjson/hjson-go/v4\"\n    \"fmt\"\n)\n\nfunc main() {\n    // Now let's look at decoding Hjson data into Go\n    // values.\n    sampleText := []byte(`\n    {\n        # specify rate in requests/second\n        rate: 1000\n        array:\n        [\n            foo\n            bar\n        ]\n    }`)\n\n    // We need to provide a variable where Hjson\n    // can put the decoded data.\n    var dat map[string]interface{}\n\n    // Decode with default options and check for errors.\n    if err := hjson.Unmarshal(sampleText, \u0026dat); err != nil {\n        panic(err)\n    }\n    // short for:\n    // options := hjson.DefaultDecoderOptions()\n    // err := hjson.UnmarshalWithOptions(sampleText, \u0026dat, options)\n    fmt.Println(dat)\n\n    // In order to use the values in the decoded map,\n    // we'll need to cast them to their appropriate type.\n\n    rate := dat[\"rate\"].(float64)\n    fmt.Println(rate)\n\n    array := dat[\"array\"].([]interface{})\n    str1 := array[0].(string)\n    fmt.Println(str1)\n\n\n    // To encode to Hjson with default options:\n    sampleMap := map[string]int{\"apple\": 5, \"lettuce\": 7}\n    hjson, _ := hjson.Marshal(sampleMap)\n    // short for:\n    // options := hjson.DefaultOptions()\n    // hjson, _ := hjson.MarshalWithOptions(sampleMap, options)\n    fmt.Println(string(hjson))\n}\n```\n\n## Unmarshal to Go structs\n\nIf 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()](https://pkg.go.dev/encoding/json#Unmarshal).\n\n```go\n\npackage main\n\nimport (\n    \"github.com/hjson/hjson-go/v4\"\n    \"fmt\"\n)\n\ntype Sample struct {\n    Rate  int\n    Array []string\n}\n\ntype SampleAlias struct {\n    Rett    int      `json:\"rate\"`\n    Ashtray []string `json:\"array\"`\n}\n\nfunc main() {\n    sampleText := []byte(`\n    {\n        # specify rate in requests/second\n        rate: 1000\n        array:\n        [\n            foo\n            bar\n        ]\n    }`)\n\n    // unmarshal\n    var sample Sample\n    hjson.Unmarshal(sampleText, \u0026sample)\n\n    fmt.Println(sample.Rate)\n    fmt.Println(sample.Array)\n\n    // unmarshal using json tags on struct fields\n    var sampleAlias SampleAlias\n    hjson.Unmarshal(sampleText, \u0026sampleAlias)\n\n    fmt.Println(sampleAlias.Rett)\n    fmt.Println(sampleAlias.Ashtray)\n}\n```\n\n## Comments on struct fields\n\nBy 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.\n\n```go\n\npackage main\n\nimport (\n    \"github.com/hjson/hjson-go/v4\"\n    \"fmt\"\n)\n\ntype foo struct {\n    A string `json:\"x\" comment:\"First comment\"`\n    B int32  `comment:\"Second comment\\nLook ma, new lines\"`\n    C string\n    D int32\n}\n\nfunc main() {\n    a := foo{A: \"hi!\", B: 3, C: \"some text\", D: 5}\n    buf, err := hjson.Marshal(a)\n    if err != nil {\n        fmt.Println(err)\n    }\n\n    fmt.Println(string(buf))\n}\n```\n\nOutput:\n\n```\n{\n  # First comment\n  x: hi!\n\n  # Second comment\n  # Look ma, new lines\n  B: 3\n\n  C: some text\n  D: 5\n}\n```\n\n## Read and write comments\n\nThe only way to read comments from Hjson input is to use a destination variable of type *hjson.Node* or *\u0026ast;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 *\u0026ast;hjson.OrderedMap*. All of the elements in `[]interface{}` or *\u0026ast;hjson.OrderedMap* will be of type *\u0026ast;hjson.Node* in trees created by *hjson.Unmarshal*, but the *hjson.Node* convenience functions unpack the actual values from them.\n\nWhen *hjson.Node* or *\u0026ast;hjson.Node* is used as destination for Hjson unmarshal the output will be a tree of *\u0026ast;hjson.Node* where all of the values contained in tree nodes will be of these types:\n\n*\t`nil` (no type)\n*\t`float64` \u0026nbsp;\u0026nbsp;(if *UseJSONNumber* == `false`)\n*\t*json.Number* \u0026nbsp;\u0026nbsp;(if *UseJSONNumber* == `true`)\n*\t`string`\n*\t`bool`\n*\t`[]interface{}`\n*\t*\u0026ast;hjson.OrderedMap*\n\nThese 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.\n\nThe 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`.\n\n```go\n\npackage main\n\nimport (\n    \"fmt\"\n\n    \"github.com/hjson/hjson-go/v4\"\n)\n\nfunc main() {\n    // Now let's look at decoding Hjson data into hjson.Node.\n    sampleText := []byte(`\n    {\n        # specify rate in requests/second\n        rate: 1000\n        array:\n        [\n            foo\n            bar\n        ]\n    }`)\n\n    var node hjson.Node\n    if err := hjson.Unmarshal(sampleText, \u0026node); err != nil {\n        panic(err)\n    }\n\n    node.NK(\"array\").Cm.Before = `        # please specify an array\n        `\n\n    if _, _, err := node.NKC(\"subMap\").SetKey(\"subVal\", 1); err != nil {\n        panic(err)\n    }\n\n    outBytes, err := hjson.Marshal(node)\n    if err != nil {\n        panic(err)\n    }\n\n    fmt.Println(string(outBytes))\n}\n```\n\nOutput:\n\n```\n\n    {\n        # specify rate in requests/second\n        rate: 1000\n        # please specify an array\n        array:\n        [\n            foo\n            bar\n        ]\n  subMap: {\n    subVal: 1\n  }\n    }\n```\n\n\n## Type ambiguity\n\nHjson 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.\n\nThe 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:\n\n```go\n\npackage main\n\nimport (\n    \"github.com/hjson/hjson-go/v4\"\n    \"fmt\"\n)\n\ntype foo struct {\n  A string\n}\n\nfunc main() {\n    var dest foo\n    err := hjson.Unmarshal([]byte(`a: 3`), \u0026dest)\n    if err != nil {\n        fmt.Println(err)\n    }\n\n    fmt.Println(dest)\n}\n```\n\nOutput:\n\n```\n{3}\n```\n\nString pointer destinations can be set to `nil` by writing `null` in an Hjson file. The same goes for a pointer destination of any type that implements `UnmarshalText()`.\n\n## ElemTyper interface\n\nIf 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.\n\nExample implementation for a generic ordered map:\n\n```go\n\nfunc (o *OrderedMap[T]) ElemType() reflect.Type {\n  return reflect.TypeOf((*T)(nil)).Elem()\n}\n```\n\n# API\n\n[![godoc](https://godoc.org/github.com/hjson/hjson-go/v4?status.svg)](https://godoc.org/github.com/hjson/hjson-go/v4)\n\n# History\n\n[see releases](https://github.com/hjson/hjson-go/releases)\n","funding_links":[],"categories":["配置","Configuration","Go","配置管理 `配置解析库`","\u003cspan id=\"组态-configuration\"\u003e组态 Configuration\u003c/span\u003e","配置管理","Uncategorized"],"sub_categories":["标准CLI","Standard CLI","Advanced Console UIs","\u003cspan id=\"高级控制台用户界面-advanced-console-uis\"\u003e高级控制台用户界面 Advanced Console UIs\u003c/span\u003e","标准 CLI"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhjson%2Fhjson-go","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhjson%2Fhjson-go","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhjson%2Fhjson-go/lists"}