当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > 在Go语言程序中使用gojson来解析JSON格式文件

在Go语言程序中使用gojson来解析JSON格式文件

2017年12月08日  | 移动技术网IT编程  | 我要评论

gojson是快速解析json数据的一个golang包,你使用它可以快速的查找json内的数据
安装

 go get github.com/widuu/gojson

使用简介

结构

复制代码 代码如下:

type js struct {
    data interface{}
}

(1) func json(data) *js data为string类型,初始化js结构,解析json并且return js.data
复制代码 代码如下:

json := `{"from":"en","to":"zh"}`
c1 := gojson.json(json) //&{map[from:en to:zh]}

(2) func (*js) get() *js 获取简单json中的某个值,递归查找,return js.data
复制代码 代码如下:

json := `{"from":"en","to":"zh","trans_result":{"src":"today","dst":"\u4eca\u5929"},"result":["src","today","dst","\u4eca\u5929"]}`

c2 := gojson.json(json).get("trans_result").get("dst")
fmt.println(c2) //&{今天}

c2 := gojson.json(json).get("from")
fmt.println(c2) //&{en}


(3) func (*js)tostring()string 将单个数据转化成string类型,因为string类型转其它类型都比较好转就让数据返回string
复制代码 代码如下:

c2 := gojson.json(json).get("from").tostring()
fmt.println(c2) //en

(4) func (j *js) getpath(args ...string) *js 通过输入string的多个参数来获取某个值,json数据一定要是递归的
复制代码 代码如下:

c4 := gojson.json(json).getpath("trans_result", "src").tostring()
fmt.println(c4)  //today

(5) func (j *js) arrayindex(i int) string 获取json数据中数组结构的值,根据输入的num来返回对应的值,仅限于处理{“result”:[“src”,”today”,”dst”,”\u4eca\u5929″]}中[]内的值
复制代码 代码如下:

json := `{"from":"en","to":"zh","trans_result":{"src":"today","dst":"\u4eca\u5929"},"result":["src","today","dst","\u4eca\u5929"]}`
c7 := gojson.json(json).get("result").arrayindex(1)
fmt.println(c7) //src

(6) func (j *js) getkey(key string, i int) *js 这个函数是针对数据中有重复数据,取值,使用js.data必须是[]interface{}类型,这个是百度翻译时候返回的js可能会用到
复制代码 代码如下:

json1 := `{"from":"en","to":"zh","trans_result":[{"src":"today","dst":"\u4eca\u5929"},{"src":"tomorrow","dst":"\u660e\u5929"}]}`
c8 := gojson.json(json1).get("trans_result").getkey("src", 1).tostring()
fmt.println(c8) //则返回trans_result第一组中的src today

(7) func (j *js) toarray() (k, d []string)将json数据转换成key []string{} value []string{} 一一对应的数组,只能使用到二级 不能到多级
复制代码 代码如下:

c9k, c9v := gojson.json(json1).get("trans_result").toarray()
fmt.println(c9k, c9v) //[src dst src dst] [today 今天 tomorrow 明天]

c3k, c3v := gojson.json(json).getindex(1).toarray()
fmt.println(c3k, c3v) //    [from] [en]


(8) func (j *js) getindex(i int) *js 根据i返回json内的数据,可以逐级查找
复制代码 代码如下:

json1 := `{"from":"en","to":"zh","trans_result":[{"src":"today","dst":"\u4eca\u5929"},{"src":"tomorrow","dst":"\u660e\u5929"}]}`

c10 := gojson.json(json1).getindex(3).getindex(1).getindex(1).get("src").tostring()
fmt.println(c10) //today


(9) func (j *js) stringtoarray() []string 将{“result”:[“src”,”today”,”dst”,”\u4eca\u5929″]}数据json中的result对应的数据,返回成[]string的slice
复制代码 代码如下:

c11 := gojson.json(json).get("result").stringtoarray()
fmt.println(c11) //[src today dst 今天]

(10) func (j *js) type() 打印测试用,打印数据类型
复制代码 代码如下:

gojson.json(json).get("result").type()  //[]interface {}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网