2 回答

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
我會(huì)創(chuàng)建一個(gè)實(shí)現(xiàn)io.Reader
接口的結(jié)構(gòu),并使用該讀取器作為翻譯基礎(chǔ):您可以使用它來逐塊獲取 JSON 輸入,并檢測(cè)您何時(shí)使用需要更改的鍵,因此將其翻譯蒼蠅。
然后,您只需使用 aio.Copy
將整個(gè)文件讀入另一個(gè)文件。
有關(guān)示例,請(qǐng)參閱text.transform包依賴關(guān)系圖...

TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以使用像megajson這樣的流式 JSON 解碼器:
// Transform 'title' strings into Title case
func TitleizeJSON(r io.Reader, w io.Writer) error {
buf := new(bytes.Buffer)
r = io.TeeReader(r, buf)
s := scanner.NewScanner(r)
var prevTok int
var prevPos int
wasTitle := false
titleField := []byte("title")
for {
// read the next json token
tok, data, err := s.Scan()
if err == io.EOF {
return nil
} else if err != nil {
return err
}
// calculate the position in the buffer
pos := s.Pos()
off := pos - prevPos
switch tok {
// if this is a string
case scanner.TSTRING:
// if the previous string before a : was 'title', then
// titlelize it
if prevTok == scanner.TCOLON && wasTitle {
// grab the first part of the buffer and skip
// the first ", the titleize the rest
data = buf.Bytes()[:off][1:]
copy(data, bytes.Title(data))
wasTitle = false
} else {
wasTitle = bytes.Equal(data, titleField)
}
}
// now send the data to the writer
data = buf.Bytes()
_, err = w.Write(data[:off])
if err != nil {
return err
}
// reset the buffer (so it doesn't grow forever)
nbuf := make([]byte, len(data)-off)
copy(nbuf, data[off:])
buf.Reset()
buf.Write(nbuf)
// for the next go-around
prevTok = tok
prevPos = pos
}
}
這應(yīng)該可以即時(shí)進(jìn)行標(biāo)題化。我能想到的一個(gè)問題是,如果你有一個(gè)非常大的字符串。
- 2 回答
- 0 關(guān)注
- 215 瀏覽
添加回答
舉報(bào)