JSON json.Decoder.
Decoder.Decode() () , . , - "" JSON, JSON, , Decoder.Decode() JSON ( ).
, , , JSON. Decoder.Token(), () JSON . , .
, "" ( ) " ", , JSON, .
, .
JSON:
{
"somefield": "value",
"otherfield": "othervalue",
"items": [
{ "id": "1", "data": "data1" },
{ "id": "2", "data": "data2" },
{ "id": "3", "data": "data3" },
{ "id": "4", "data": "data4" }
]
}
items, " ", :
type LargeObject struct {
Id string 'json:"id"'
Data string 'json:"data"'
}
JSON, / .
:
he := func(err error) {
if err != nil {
log.Fatal(err)
}
}
. Go string. HTTP, , json.Decoder:
dec := json.NewDecoder(res.Body)
, :
dec := json.NewDecoder(strings.NewReader(jsonStream))
t, err := dec.Token()
he(err)
if delim, ok := t.(json.Delim); !ok || delim != '{' {
log.Fatal("Expected object")
}
for dec.More() {
t, err = dec.Token()
he(err)
prop := t.(string)
if t != "items" {
var v interface{}
he(dec.Decode(&v))
log.Printf("Property '%s' = %v", prop, v)
continue
}
t, err := dec.Token()
he(err)
if delim, ok := t.(json.Delim); !ok || delim != '[' {
log.Fatal("Expected array")
}
for dec.More() {
lo := LargeObject{}
he(dec.Decode(&lo))
fmt.Printf("Item: %+v\n", lo)
}
t, err = dec.Token()
he(err)
if delim, ok := t.(json.Delim); !ok || delim != ']' {
log.Fatal("Expected array closing")
}
}
t, err = dec.Token()
he(err)
if delim, ok := t.(json.Delim); !ok || delim != '}' {
log.Fatal("Expected object closing")
}
:
2009/11/10 23:00:00 Property 'somefield' = value
2009/11/10 23:00:00 Property 'otherfield' = othervalue
Item: {Id:1 Data:data1}
Item: {Id:2 Data:data2}
Item: {Id:3 Data:data3}
Item: {Id:4 Data:data4}
Go Playground.