HuJSON: JSON for Humans (comments and trailing commas)

HuJSON - Human JSON

The HuJSON decoder is a JSON decoder that also allows

  • comments, both /* ... */ and // to end of line
  • trailing commas on arrays and object members

It is a soft fork of the Go standard library encoding/json package. The plan is to merge in all changes from each Go release.

Currently HuJSON is based on Go 1.13.

Grammar

The changes to the JSON grammar are:

--- grammar.json
+++ grammar.hujson
@@ -1,13 +1,31 @@
 members
 	member
+	member ',' ws
 	member ',' members
 
 elements
 	element
+	element ',' ws
 	element ',' elements
 
+comments
+	"*/"
+	comment comments
+
+comment
+	'0000' . '10FFFF'
+
+linecomments
+	'\n'
+	linecomment
+
+linecomment
+	'0000' . '10FFFF' - '\n'
+
 ws
 	""
+	"/*" comments
+	"//" linecomments
 	'0020' ws
 	'000A' ws
 	'000D' ws
Owner
Tailscale
Tailscale is a WireGuard-based app that makes secure, private networks easy for teams of any scale.
Tailscale
Comments
  • feat(hujsonfmt): add basic hujsonfmt CLI command

    feat(hujsonfmt): add basic hujsonfmt CLI command

    Added as a separate Go module with its own go.mod file to avoid polluting the root module's dependency tree.

    The CLI interface and flags are very similar to gofmt:

    $ hujsonfmt -h
    usage: hujsonfmt [flags] [path ...]
      -d	display diffs instead of rewriting files
      -l	list files whose formatting differs from hujsonfmt's
      -m	minify results
      -s	standardize results to plain JSON
      -w	write result to (source) file instead of stdout
    

    Given paths can either point directly to a file, or to a directory. In the case of a directory, it will be recursively walked finding all *.hujson files.

    Input can also be provided via stdin if no paths are provided, or a single path of "-" is provided:

    $ echo '{\n// hai\n"foo":"bar"}' | ./hujsonfmt
    {
    	// hai
    	"foo": "bar",
    }
    
  • Turn `ObjectMember` into a named type

    Turn `ObjectMember` into a named type

    I'm not sure why ObjectMember is defined as a type alias instead of a named type. In practice, it's probably not a big deal, but it makes autocomplete weird.

  • Initial commit of a HuJSON AST parser and packer

    Initial commit of a HuJSON AST parser and packer

    This package provides a HuJSON parser into an AST represented by the following Go types:

    • Value: A JSON literal, object, or array with surrounding whitespace/comments.
    • ValueTrimmed: A JSON value without surrounding whitespace/comments.
    • Extra: Raw bytes of whitespace and comments.
    • Literal: Raw bytes of a JSON literal (i.e., null, boolean, string, or number).
    • Object: A JSON object.
    • Array: A JSON array.

    The Parse function parses raw HuJSON input as a Value. The Value.Pack method serializes the AST as raw HuJSON output.

    The intention is to delete the fork of "encoding/json" currently here once we migrate all usages to the new code.

  • update for go1.14

    update for go1.14

    The base of hujson is go1.13, the specific commit number is in https://github.com/tailscale/hujson/commit/e2a9696a57f84acb1a0b2d50b986b180be9ed8c4. We should git diff go/src/pkg/encoding/json between that commit and go1.14 and apply the diff to hujson.

  • Tests expecting failure accepts success

    Tests expecting failure accepts success

    Some tests that expect a parse error pass even when no such error occurs. For example, the test suite passes after the following change:

    diff --git a/decode_test.go b/decode_test.go
    index 43e9b4a..2d24fcb 100644
    --- a/decode_test.go
    +++ b/decode_test.go
    @@ -457,8 +457,8 @@ var unmarshalTests = []unmarshalTest{
            // syntax errors
            {in: `{"X": "foo", "Y"}`, err: &SyntaxError{"invalid character '}' after object key", 17}},
            {in: `[1, 2, 3+]`, err: &SyntaxError{"invalid character '+' after array element", 9}},
    -       {in: `{"X":12x}`, err: &SyntaxError{"invalid character 'x' after object key:value pair", 8}, useNumber: true},
    -       {in: `[2, 3`, err: &SyntaxError{msg: "unexpected end of JSON input", Offset: 5}},
    +       {in: `{"X":"12x"}`, err: &SyntaxError{"invalid character 'x' after object key:value pair", 8}, useNumber: true},
    +       {in: `[2, 3]`, err: &SyntaxError{msg: "unexpected end of JSON input", Offset: 5}},
    
            // raw value errors
            {in: "\x01 42", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
    
  • format: trim whitespace in string literals

    format: trim whitespace in string literals

    We pretty much don't ever want tokens to have leading or trailing whitespaces, so this trims it as part of the string normalization process.

    Updates tailscale/tailscale#6040

  • Add Standardize helper function

    Add Standardize helper function

    This reduces the boilerplate of using hujson with json. We avoid a helper that directly wraps json.Unmarshal since there could be a new json library in the future. Let's avoid a dependency on the json Marshal/Unmarshal semantics and keep this package purely about the HuJSON syntax.

  • Delete some deprecated declarations

    Delete some deprecated declarations

    These are not referenced anywhere whether in our own source code or in any publicly available source code.

    The other deprecated declarations will also be deleted once known usages have been cleaned up.

    The hujson package has no compatibility guarantees, so deletion is permissible.

  • Fix Unmarshal

    Fix Unmarshal

    The old HuJSON parser had a bug where it couldn't handle trailing comments after the last value. The new parser has no such problem.

    As a quick fix to the deprecated Unmarshal function, use the new parser to strip HuJSON-specific artifacts and then pass the standardized output to Unmarshal.

  • FR: Publish the .hujson schema to schemastore.org

    FR: Publish the .hujson schema to schemastore.org

    To use the megalinter and linter in many IDEs is a release the json schema on https://schemastore.org required.

    https://github.com/SchemaStore/schemastore

  • How to update parsed hujson's Value?

    How to update parsed hujson's Value?

    I've been testing hujson and trying to read, edit, then write the edited data back to my json file. But I can't find an example in the docs or the source code on how to write back an edited object while preserving the commas and comments. Note the jwcc.Value = ??? in my example code:

    test.json

    {
      "foo": "bar" // some comment
    }
    

    main.go

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"os"
    
    	"github.com/tailscale/hujson"
    )
    
    func main() {
    	fileBytes, err := os.ReadFile("test.json")
    	if err != nil {
    		fmt.Printf("error reading file: %s", err)
    	}
    	// read json with commas and comments
    	jwccData, err := hujson.Parse(fileBytes)
    
    	// get standard json data into tst
    	tst := &test{}
    	standardData, err := hujson.Standardize(fileData)
    	json.Unmarshal(standardData, tst)
    
    	// update standard data
    	tst.Foo = "bar-moodified"
    
    	// TODO: HOW to put the updated tst as jwccData.Value 
    	jwcc.Value = ???
    
    	// write the updated tst data back to test.json
    	os.WriteFile("test-updated.json", preservedJSON.Pack(), 0644)
    
    	fmt.Println("Preserved JSON Data updated")
    	fmt.Println(preservedJSON)
    }
    
    type test struct {
    	Foo string `json:"foo"`
    }
    
    
    
  • Add NewNames and Value.NormalizeNames

    Add NewNames and Value.NormalizeNames

    The NewNames function produces a map of canonical names from a Go struct. It can be passed to Value.NormalizeNames to normalizes case-insensitive matches to a JSON object name to the canonical name.

Related tags
JSON with comments for Go!
JSON with comments for Go!

JSON with comments for Go! JSONC is a superset of JSON which supports comments. JSON formatted files are readable to humans but the lack of comments d

Nov 23, 2022
Package json implements encoding and decoding of JSON as defined in RFC 7159

Package json implements encoding and decoding of JSON as defined in RFC 7159. The mapping between JSON and Go values is described in the documentation for the Marshal and Unmarshal functions

Jun 26, 2022
Json-go - CLI to convert JSON to go and vice versa
Json-go - CLI to convert JSON to go and vice versa

Json To Go Struct CLI Install Go version 1.17 go install github.com/samit22/js

Jul 29, 2022
JSON Spanner - A Go package that provides a fast and simple way to filter or transform a json document

JSON SPANNER JSON Spanner is a Go package that provides a fast and simple way to

Sep 14, 2022
Get JSON values quickly - JSON parser for Go
Get JSON values quickly - JSON parser for Go

get json values quickly GJSON is a Go package that provides a fast and simple way to get values from a json document. It has features such as one line

Dec 28, 2022
JSON diff library for Go based on RFC6902 (JSON Patch)

jsondiff jsondiff is a Go package for computing the diff between two JSON documents as a series of RFC6902 (JSON Patch) operations, which is particula

Dec 4, 2022
Fast JSON encoder/decoder compatible with encoding/json for Go
Fast JSON encoder/decoder compatible with encoding/json for Go

Fast JSON encoder/decoder compatible with encoding/json for Go

Jan 6, 2023
Fast JSON parser and validator for Go. No custom structs, no code generation, no reflection

fastjson - fast JSON parser and validator for Go Features Fast. As usual, up to 15x faster than the standard encoding/json. See benchmarks. Parses arb

Jan 5, 2023
Fast and flexible JSON encoder for Go
Fast and flexible JSON encoder for Go

Jettison Jettison is a fast and flexible JSON encoder for the Go programming language, inspired by bet365/jingo, with a richer features set, aiming at

Dec 21, 2022
/ˈdʏf/ - diff tool for YAML files, and sometimes JSON
/ˈdʏf/ - diff tool for YAML files, and sometimes JSON

dyff is inspired by the way the old BOSH v1 deployment output reported changes from one version to another by only showing the parts of a YAML file that change.

Dec 29, 2022
tson is JSON viewer and editor written in Go
tson is JSON viewer and editor written in Go

tson tson is JSON viewer and editor written in Go. This tool displays JSON as a tree and you can search and edit key or values. Support OS Mac Linux I

Nov 2, 2022
JSONata in Go Package jsonata is a query and transformation language for JSON

JSONata in Go Package jsonata is a query and transformation language for JSON. It's a Go port of the JavaScript library JSONata.

Nov 8, 2022
Slow and unreliable JSON parser generator (in progress)

VivaceJSON Fast and reliable JSON parser generator Todo List parse fields parse types generate struct generate (keypath+key) to struct Value Mapping F

Nov 26, 2022
Kazaam was created with the goal of supporting easy and fast transformations of JSON data with Golang

kazaam Description Kazaam was created with the goal of supporting easy and fast transformations of JSON data with Golang. This functionality provides

Sep 17, 2021
Golang JSON decoder supporting case-sensitive, number-preserving, and strict decoding use cases

Golang JSON decoder supporting case-sensitive, number-preserving, and strict decoding use cases

Dec 9, 2022
Easy JSON parsing, stringifying, and accesing

Easy JSON parsing, stringifying, and accesing

Nov 23, 2021
A tool to aggregate and mine data from JSON reports of Go tests.

teststat A tool to aggregate and mine data from JSON reports of Go tests. Why? Mature Go projects often have a lot of tests, and not all of them are i

Sep 15, 2022
json encoding and decoding

jx Package jx implements encoding and decoding of json [RFC 7159]. Lightweight fork of jsoniter. go get github.com/go-faster/jx Usage and examples Roa

Dec 27, 2022
Search and output the value of JSON by it's path.

Search and output the value of JSON by it's path.

Dec 19, 2021