dongzhong9055 2018-10-03 06:10
浏览 46
已采纳

有效地确定JSON标签

I have a bunch of JSON files, each containing a very large array of complex data. The JSON files look something like:

ids.json

{
    "ids": [1,2,3]
}

names.json:

{
    "names": ["Tyrion","Jaime","Cersei"]
}

and so on. (In reality, the array elements are complex struct objects with 10s of fields)

I want to extract just the tag that specifies what kind of array it contains. Currently I'm using encoding/json to unmarshal the whole file into a map[string]interface{} and iterate through the map but that is too costly an operation.

Is there a faster way of doing this, preferably without the involvement of unmarshaling entire data?

  • 写回答

2条回答 默认 最新

  • dongzhiyi2006 2018-10-03 06:50
    关注

    You can offset the reader right after the opening curly brace then use json.Decoder to decode only the first token from the reader

    Something along these lines

    sr := strings.NewReader(`{
        "ids": [1,2,3]
    }`)
    
    for {
        b, err := sr.ReadByte()
        if err != nil {
            fmt.Println(err)
            return
        }
        if b == '{' {
            break
        }
    }
    
    d := json.NewDecoder(sr)
    
    var key string
    err := d.Decode(&key)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    fmt.Println(key)
    

    https://play.golang.org/p/xJJEqj0tFk9

    Additionally you may wrap your io.Reader you obtained from open with bufio.Reader to avoid multiple single-byte writes

    This solution assumes contents is a valid JSON object. Not that you could avoid that anyway.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?