• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

jmoiron/jsonq: simple json field access for golang

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

jmoiron/jsonq

开源软件地址:

https://github.com/jmoiron/jsonq

开源编程语言:

Go 97.9%

开源软件介绍:

jsonq

Build Status Godoc license

Simplify your golang json usage by extracting fields or items from arrays and objects with a simple, hierarchical query. API Documentation on godoc.org.

This package is meant to make working with complex feeds a bit more easy. If you have simple feeds you want to model with struct types, check out jflect, which will create struct definitions given a json document.

installing

go get github.com/jmoiron/jsonq

usage

Given some json data like:

{
	"foo": 1,
	"bar": 2,
	"test": "Hello, world!",
	"baz": 123.1,
	"array": [
		{"foo": 1},
		{"bar": 2},
		{"baz": 3}
	],
	"subobj": {
		"foo": 1,
		"subarray": [1,2,3],
		"subsubobj": {
			"bar": 2,
			"baz": 3,
			"array": ["hello", "world"]
		}
	},
	"bool": true
}

Decode it into a map[string]interface{}:

import (
	"strings"
	"encoding/json"
	"github.com/jmoiron/jsonq"
)

data := map[string]interface{}{}
dec := json.NewDecoder(strings.NewReader(jsonstring))
dec.Decode(&data)
jq := jsonq.NewQuery(data)

From here, you can query along different keys and indexes:

// data["foo"] -> 1
jq.Int("foo")

// data["subobj"]["subarray"][1] -> 2
jq.Int("subobj", "subarray", "1")

// data["subobj"]["subarray"]["array"][0] -> "hello"
jq.String("subobj", "subsubobj", "array", "0")

// data["subobj"] -> map[string]interface{}{"subobj": ...}
obj, err := jq.Object("subobj")

Missing keys, out of bounds indexes, and type failures will return errors. For simplicity, integer keys (ie, {"0": "zero"}) are inaccessible by jsonq as integer strings are assumed to be array indexes.

The Int and Float methods will attempt to parse numbers from string values to ease the use of many real world feeds which deliver numbers as strings.

Suggestions/comments please tweet @jmoiron




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap