MarshalJSON without having all objects in memory at once

后端 未结 2 1667
情歌与酒
情歌与酒 2021-01-13 04:48

I want to use json.Encoder to encode a large stream of data without loading all of it into memory at once.

// I want to marshal this
t := struct         


        
2条回答
  •  渐次进展
    2021-01-13 05:32

    You can unpack the channel in the MarshalJSON method in your struct like this:

    type S struct {
        Foo string
        Bar chan string 
    }
    
    func (s *S) MarshalJSON() (b []byte, err error) {
        b, err := json.Marshal(s.Foo)
    
        if err != nil { return nil, err }
    
        for x := range s.Bar {
            tmp, err := json.Marshal(x)
    
            if err != nil { return nil, err }
    
            b = append(b, tmp...)
        }
    
        return
    }
    

提交回复
热议问题