如何用golang源码分析simplejson

如何用golang源码分析simplejson,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

背景:
1,golang自带的json解析库encoding/json提供了json字符串到json对象的相互转换,在json字符串比较简单的情况下还是挺好用的,但是当json字符串比较复杂或者嵌套比较多的时候,就显得力不从心了,不可能用encoding/json那种为每个嵌套字段定义一个struct类型的方式,这时候使用simplejson库能够很方便的解析。

2,当被解析的json数据不一定完整的时候,使用标准库经常会解析失败,但是解析部分数据也是我们能接受的,这时可以用simplejson

源码

如何用golang源码分析simplejson  simplejson 第1张

可以看到,基本思路是将数据解析进一个interface{},然后进行类型推断。

底层还是用的标准库

func NewJson(body []byte) (*Json, error) {  j := new(Json)  err := j.UnmarshalJSON(body)  }    func (j *Json) UnmarshalJSON(p []byte) error {  dec := json.NewDecoder(bytes.NewBuffer(p))  dec.UseNumber()  return dec.Decode(&j.data)}    func (j *Json) Map() (map[string]interface{}, error) {  if m, ok := (j.data).(map[string]interface{}); ok {    return m, nil            func (j *Json) Array() ([]interface{}, error) {  if a, ok := (j.data).([]interface{}); ok {    return a, nil

 json.Decoder vs json.Unmarshal

son的反序列化方式有两种:

Use json.Unmarshal passing the entire response string

// func Unmarshal(data []byte, v interface{}) error

data, err := ioutil.ReadAll(resp.Body)

if err == nil && data != nil {

    err = json.Unmarshal(data, value)

}

using json.NewDecoder.Decode

// func NewDecoder(r io.Reader) *Decoder

// func (dec *Decoder) Decode(v interface{}) error

err = json.NewDecoder(resp.Body).Decode(value)

这两种方法看似差不多,但有不同的应用场景

Use json.Decoder if your data is coming from an io.Reader stream, or you need to decode multiple values from a stream of data.

For the case of reading from an HTTP request, I’d pick json.Decoder since you’re obviously reading from a stream.

Use json.Unmarshal if you already have the JSON data in memory.

从文件中读入一个巨大的json数组用json.Decoder

json.Decoder会一个一个元素进行加载,不会把整个json数组读到内存里面

从文件中读入json流用json.Decode

本来就以[]byte存在于内存中的用json.Unmarshal

看完上述内容,你们掌握如何用golang源码分析simplejson的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注蜗牛博客行业资讯频道,感谢各位的阅读!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接