File: DOCUMENTATION.md

package info (click to toggle)
golang-github-muhammadmuzzammil1998-jsonc 0.0~git20201229.615b091-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 1,128 kB
  • sloc: makefile: 2
file content (111 lines) | stat: -rw-r--r-- 2,064 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# Documentation for JSONC

## ToJSON()

Converts JSONC to JSON equivalent by removing all comments.

```go
func ToJSON(b []byte) []byte
```

Example:

```go
func main() {
  j := []byte(`{"foo": /*comment*/ "bar"}`)
  jc := jsonc.ToJSON(j)
  fmt.Println(string(jc)) // {"foo":"bar"}
}
```

## ReadFromFile()

Reads jsonc file and returns JSONC and JSON encodings.

```go
func ReadFromFile(filename string) ([]byte, []byte, error)
```

Example:

```go
func main() {
  jc, j, err := jsonc.ReadFromFile("data.jsonc")
  if err != nil {
    log.Fatal(err)
  }
  // jc and j contains JSONC and JSON, respectively.
}
```

## Unmarshal()

Parses the JSONC-encoded data and stores the result in the value pointed to by passed interface. Equivalent of calling `json.Unmarshal(jsonc.ToJSON(data), v)`.

```go
func Unmarshal(data []byte, v interface{}) error
```

Example:

```go
func main(){
  type UnmarshalTest struct {
    Foo    string `json:"foo"`
    True   bool   `json:"true"`
    Num    int    `json:"number"`
    Object struct {
      Test string `json:"test"`
    } `json:"object"`
    Array []int `json:"array"`
  }

  un := UnmarshalTest{}
  jc, _, _ := jsonc.ReadFromFile("data.jsonc")
  if err := jsonc.Unmarshal(jc, &un); err != nil {
    log.Fatal("Unable to unmarshal.", err)
  }
  fmt.Println(string(jc))
  fmt.Printf("%+v", un)
}
```

Output:

```sh
$ go run .\main.go
{
  /* This is an example
     for block comment. */
  "foo": "bar foo", // Comments can
  "true": false, // Improve readability.
  "number": 42, // Number will always be 42.
  /* Comments are ignored while
     generating JSON from JSONC. */
  "object": {
    "test": "done"
  },
  "array": [1, 2, 3]
}

{Foo:bar foo True:false Num:42 Object:{Test:done} Array:[1 2 3]}
```

## Valid()

Reports whether data is a valid JSONC encoding or not.

```go
func Valid(data []byte) bool
```

Example:

```go
func main() {
  jc1 := []byte(`{"foo":/*comment*/"bar"}`)
  jc2 := []byte(`{"foo":/*comment/"bar"}`)
  fmt.Println(jsonc.Valid(jc1)) // true
  fmt.Println(jsonc.Valid(jc2)) // false
}
```