我正在读取JSON以响应HTTP端点,并希望提取嵌套在其中的对象数组的内容。响应可能很大,所以我正在尝试使用流方法而不是仅使用json。 JSON如下所示:
{
"useless_thing_1": { /* etc */ },
"useless_thing_2": { /* etc */ },
"the_things_i_want": [
{ /* complex object I want to json.Unmarshal #1 */ },
{ /* complex object I want to json.Unmarshal #2 */ },
{ /* complex object I want to json.Unmarshal #3 */ },
/* could be many thousands of these */
],
"useless_thing_3": { /* etc */ },
}
Go随附的json库具有json.Unmarshal
,它对于完整的JSON对象非常有效。它还具有json.Decoder
,可以解组全部对象或提供单独的令牌。我可以使用此令牌生成器仔细地进行操作并提取内容,但是这样做的逻辑有些复杂,因此在将其作为令牌读取后,我无法轻易在对象上仍然使用json.Unmarshal
。
json.Decoder被缓冲,这使得很难读取一个对象(即{ /* complex object I want to json.Unmarshal #1 */ }
),然后自己使用,
并创建一个新的json.Decoder
-因为它将尝试使用逗号本身。这是我尝试过但仍无法完成的方法。
我正在寻找一个更好的解决方案。当我尝试手动使用逗号时,这是损坏的代码:
// code here that naively looks for `"the_things_i_want": [` and
// puts the next bytes after that in `buffer`
// this is the rest of the stream starting from `{ /* complex object I want to json.Unmarshal #1 */ },`
in := io.MultiReader(buffer, res.Body)
dec := json.NewDecoder(in)
for {
var p MyComplexThing
err := dec.Decode(&p)
if err != nil {
panic(err)
}
// steal the comma from in directly - this does not work because the decoder buffer's its input
var b1 [1]byte
_, err = io.ReadAtLeast(in, b1[:], 1) // returns random data from later in the stream
if err != nil {
panic(err)
}
switch b1[0] {
case ',':
// skip over it
case ']':
break // we're done
default:
panic(fmt.Errorf("Unexpected result from read %#v", b1))
}
}
使用Decoder.Token和Decoder.More将JSON文档解码为流。]>
使用Decoder.Token在文档中浏览至关注点。调用Decoder.Decode将JSON值解组为Go值。根据需要重复,以获取所有感兴趣的值。
下面是一些带有注释的代码,解释了其工作方式:
func decode(r io.Reader) error {
d := json.NewDecoder(r)
// We expect that the JSON document is an object.
if err := expect(d, json.Delim('{')); err != nil {
return err
}
// While there are fields in the object...
for d.More() {
// Get field name
t, err := d.Token()
if err != nil {
return err
}
// Skip value if not the field that we are looking for.
if t != "the_things_i_want" {
if err := skip(d); err != nil {
return err
}
continue
}
// We expect JSON array value for the field.
if err := expect(d, json.Delim('[')); err != nil {
return err
}
// While there are more JSON array elements...
for d.More() {
// Unmarshal and process the array element.
var m map[string]interface{}
if err := d.Decode(&m); err != nil {
return err
}
fmt.Printf("found %v\n", m)
}
// We are done decoding the array.
return nil
}
return errors.New("things I want not found")
}
// skip skips the next value in the JSON document.
func skip(d *json.Decoder) error {
n := 0
for {
t, err := d.Token()
if err != nil {
return err
}
switch t {
case json.Delim('['), json.Delim('{'):
n++
case json.Delim(']'), json.Delim('}'):
n--
}
if n == 0 {
return nil
}
}
}
// expect returns an error if the next token in the document is not expectedT.
func expect(d *json.Decoder, expectedT interface{}) error {
t, err := d.Token()
if err != nil {
return err
}
if t != expectedT {
return fmt.Errorf("got token %v, want token %v", t, expectedT)
}
return nil
}