-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonfiles03.go
More file actions
55 lines (43 loc) · 1.8 KB
/
jsonfiles03.go
File metadata and controls
55 lines (43 loc) · 1.8 KB
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
/* RZFeeser | Alta3 Research
Troubleshooting - Writing out JSON & exported identifiers
Within the ColorGroup struct, names are created with lowercase.
Go visibility rules for struct files are slightly ammended, but still remain. (https://pkg.go.dev/encoding/json#Marshal)
Here we are requesting our struct interact with the json package. Therefore, any names that do not follow the rules of "Exported identifiers", will not be found by the json package.
Rules for Exported identifiers include the first character being capitalized, and being declared in the package block (or a field name or method name). (https://golang.org/ref/spec#Exported_identifiers)*/
package main
import (
"encoding/json"
"os"
)
func main() {
type Person struct {
Fn string
Ln string
}
// creating a struct with some lowercase names
type ColorGroup struct {
ID int // uppercase - "OK" at function level because it is a field name
Name string // lowercase
colors []string // lowercase
p Person `json:"Person"` // lowercase (struct, not JSON tag)
}
per := Person{Fn: "RZ",
Ln: "Feeser",
}
// group is the TYPE ColorGroup
group := ColorGroup{
ID: 24601,
Name: "Greens",
colors: []string{"Moss", "Shamrock", "Lime", "Hunter"},
p: per,
}
// serialize values from struct to json format
// our struct "group" is defined in the main package
b, err := json.Marshal(group) // requesting interaction between json package and main package
// result is ONLY the "exported" (capitalized) names will be found!
if err != nil {
panic(err)
}
// print to standard out
os.Stdout.Write(b) // the "ONLY" thing that the json package could find was ColorGroup.ID!
}