Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidUTF8 = errors.New("jsonc: invalid UTF-8")
ErrInvalidUTF8 is returned by Sanitize if the data is not valid UTF-8.
Functions ¶
func HasCommentRunes ¶ added in v0.1.1
HasCommentRunes returns true if the data contains any comment rune. It checks whether the data contains any '/' character, and if so, it looks whether the previous one is a '/' or the next one is a '/' or a '*'. If not, it returns false.
Caveat: if the data contains a string that looks like a comment as '{"url": "http://example.com"}', HasCommentRunes returns true.
For example, it returns true for the following data:
{ // comment "key": "value" }
or
{ /* comment "key": "value" */ "foo": "bar" }
But also for:
{ "key": "value // comment" }
func Sanitize ¶
Sanitize removes all comments from JSONC data. It returns ErrInvalidUTF8 if the data is not valid UTF-8.
NOTE: it does not checks whether the data is valid JSON or not.
func Unmarshal ¶
Unmarshal parses the JSONC-encoded data and stores the result in the value pointed by v removing all comments from the data (if any).
It uses HasCommentRunes to check whether the data contains any comment. Note that this operation is as expensive as the larger the data. On small data sets it just adds a small overhead to the unmarshaling process, but on large data sets it may have a significant impact on performance. In such cases, it may be more efficient to call Sanitize and then the standard (or any other) library directly.
If the data contains comment runes, it calls Sanitize to remove them and returns ErrInvalidUTF8 if the data is not valid UTF-8. Note that if no comments are found, it is assumed that the given data is valid JSON-encoded and the UTF-8 validity is not checked.
Any error is reported from json.Unmarshal as is.
It uses the standard library for unmarshaling by default, but can be configured to use the jsoniter or go-json library instead by using build tags.
| tag | library | |---------------|-------------------------------| | none or both | standard library | | jsoniter | "github.com/json-iterator/go" | | go_json | "github.com/goccy/go-json" |
Example:
data := []byte(`{/* comment */"name": "John", "age": 30}`) type T struct { Name string Age int } var t T err := jsonc.Unmarshal(data, &t) ...
Example ¶
var v interface{} data := []byte(`{/* comment */"foo": "bar"}`) err := jsonc.Unmarshal(data, &v) if err != nil { panic(err) } fmt.Println(v)
Output: map[foo:bar]
Example (SanitizeError) ¶
var v interface{} invalid := []byte(`{/* comment */"foo": "invalid utf8"}`) invalid = append(invalid, []byte("\xa5")...) err := jsonc.Unmarshal(invalid, &v) fmt.Println(err)
Output: jsonc: invalid UTF-8
Types ¶
This section is empty.