Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/tidwall/jsonc

go 1.16
go 1.18
19 changes: 19 additions & 0 deletions jsonc.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package jsonc

import (
"encoding/json"
)

// ToJSON strips out comments and trailing commas and convert the input to a
// valid JSON per the official spec: https://tools.ietf.org/html/rfc8259
//
Expand All @@ -11,6 +15,21 @@ func ToJSON(src []byte) []byte {
return toJSON(src, nil)
}

// Unmarshal parses the JSONC data and stores the result in the value pointed
// to by v. It is a drop-in replacement for json.Unmarshal from encoding/json.
//
// Unmarshal supports comments (both // and /* */) and trailing commas.
func Unmarshal(data []byte, v any) error {
cleaned := ToJSON(data)
return json.Unmarshal(cleaned, v)
}

// Marshal returns the JSON encoding of v. It is a drop-in replacement for
// json.Marshal from encoding/json.
func Marshal(v any) ([]byte, error) {
return json.Marshal(v)
}

// ToJSONInPlace is the same as ToJSON, but this method reuses the input json
// buffer to avoid allocations. Do not use the original bytes slice upon return.
func ToJSONInPlace(src []byte) []byte {
Expand Down
21 changes: 21 additions & 0 deletions jsonc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,27 @@ package jsonc

import "testing"

func TestUnmarshal(t *testing.T) {
type Person struct {
Name string `json:"name"`
}

jsonc := `{
// This is a comment
"name": "John",
}`

want := Person{Name: "John"}
var got Person
err := Unmarshal([]byte(jsonc), &got)
if err != nil {
t.Fatalf("Unmarshal() error = %v", err)
}
if got != want {
t.Errorf("Unmarshal() got = %v, want %v", got, want)
}
}

func TestToJSON(t *testing.T) {
json := `
{ // hello
Expand Down