This is a creation in Article, where the information may have evolved or changed.
1. Introduction
JSON (JavaScript Object Notation) is a lightweight data interchange format. It is syntactically similar to JavaScript objects and lists. Most commonly used for communication between the Web backend and running JavaScript programs in the browser, but are also heavily used elsewhere. Its homepage: json.org, provides a very clear and concise definition of the standard.
The JSON package makes it easy to read and write JSON data in the GO program.
2. Encoding
Use the Marshal function to generate JSON data.
funcinterface{}) ([]byte, error)
Structure of the given GO data: Message
,
typestruct { string string int64}
Then gets Message
an instance of the.
m := Message{"Alice""Hello", 1294706395881547000}
Use json.Marshal
to get a JSON-formatted m.
b, err := json.Marshal(m)
If all goes well, it will be err
nil
, and will be, b
a JSON-containing data[]byte
b == []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`)
The data structure is encoded only when it is represented as a legitimate JSON.
- The JSON object supports only the strings type as the key name; You must use map[string]t to encode the Go map type (which
T
is the go type supported by any JSON package).
- Channel,complex and function types cannot be encoded.
- Looping data structures are not supported and will result in a
Marshal
dead loop.
- The pointers are encoded into the values they point to (or ' null ' if the pointer is 0).
The JSON package accesses only the struct types that expose the fields (those that start with uppercase letters), so only the structure of the exposed fields is present in the JSON output.
Sample Code :
PackageMainImport("Encoding/json" "FMT" "OS")funcMain () {typeColorgroupstruct{IDintNamestringColors []string} Group: = colorgroup{ID:1, Name:"Reds", Colors: []string{"Crimson","Red","Ruby","Maroon"},} B, err: = json. Marshal (Group)ifErr! =Nil{FMT. Println ("Error:", err)} OS. Stdout.write (b)}
3. decoding
Use the Unmarshal function to parse the JSON data.
func Unmarshal(data []byteinterface{}) error
You must first create a place to hold the parsed data.
var m Message
It is then called json.Unmarshal
, passing in a []byte
and a pointer m containing the JSON data.
err := json.Unmarshal(b, &m)
If the b
appropriate m
valid JSON data is included, then the call will be err
nil
, and then the data will be saved from the b
struct m
, just like the assignment:
m = Message{ "Alice", "Hello", Time: 1294706395881547000,}
Unmarshal
when using, how do I define a field to hold decoded data? For a given key "Foo"
, the Unmarshal
target structure is browsed to find the corresponding field. (ordered in order of precedence)
- A
"Foo"
public field labeled (more structure tags see Go spec),
- A publicly named
"Foo"
field, or
- A public field called a name
"FOO"
or some other case-insensitive "FoO"
match "Foo"
.
What if the structure of the JSON data does not exactly match the Go type?
b := []byte(`{"Name":"Bob","Food":"Pickle"}`)var m Messageerr := json.Unmarshal(b, &m)
Unmarshal
Only the fields defined in the target type are resolved. In this example, only the Name field of M is parsed, and the food field is ignored. This behavior is useful when you only want to select a small number of specific fields from the large JSON data. This also means that the private fields of any target struct will not be Unmarshal
affected.
Sample Code :
PackageMainImport("Encoding/json" "FMT")funcMain () {varJsonblob = []byte(' [{' name ': ' Platypus ', ' order ': ' Monotremata '}, {' name ': ' Quoll ', ' Order ': ' Dasyuromorphia '}] '
)typeAnimalstruct{NamestringOrderstring}varAnimals []animal ERR: = json. Unmarshal (Jsonblob, &animals)ifErr! =Nil{FMT. Println ("Error:", err)} FMT. Printf ("%+v", animals)}
4. Notes
- The key name for the custom output JSON data, followed by the inverse single quotation mark after the field type
json:" "
:
typestruct { Name string`json:"name"` string }
- If the double quotation marks are in the middle
-
, the field will not be output:
typestruct { Name string`json:"-"` string }
references
Go blog: http://blog.golang.org/json-and-go
Go programming language JSON package: https://golang.org/pkg/ encoding/json/
Rgyq Blog: http://rgyq.blog.163.com/blog/static/316125382013934153244/