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

antchfx/jsonquery: jsonq package for Go. Golang XPath query for JSON query.

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

开源软件名称:

antchfx/jsonquery

开源软件地址:

https://github.com/antchfx/jsonquery

开源编程语言:

Go 100.0%

开源软件介绍:

jsonquery

Build Status Coverage Status GoDoc Go Report Card

Overview

jsonquery is XPath query package for JSON document depended on xpath package, writing in go.

jsonquery helps you easy to extract any data from JSON using XPath query without using pre-defined object structure to unmarshal in go, saving your time.

  • htmlquery - XPath query package for HTML document

  • xmlquery - XPath query package for XML document.

Install Package

go get github.com/antchfx/jsonquery

Get Started

The below code may be help your understand what it does. We don't need pre-defined strcutre or using regexp to extract some data in JSON file, gets any data is easy and fast in jsonquery now.

s := `{
	"name":"John",
	"age":31,
	"female":false,
	"city":null
	}`
doc, err := jsonquery.Parse(strings.NewReader(s))
if err != nil {
	panic(err)
}
// iterate all json objects from child ndoes.
for _, n := range doc.ChildNodes() {
	fmt.Printf("%s: %v[%T]\n", n.Data, n.Value(), n.Value())
}
// xpath query
n := jsonquery.FindOne(doc, "//age")
fmt.Printf("age: %.2f", n.Value().(float64))
// select a child node with `age`. = jsonquery.FindOne(doc,"age") 
m := doc.SelectElement("age")

// Output:

name: John[string]
age: 31[float64]
female: false[bool]
city: <nil>[<nil>]

The default Json types and Go types are:

JSON jsonquery(go)
object interface{}
string string
number float64
boolean bool
array []interface{}
null nil

For more information about JSON & Go see the https://go.dev/blog/json

Getting Started

Load JSON from URL.

doc, err := jsonquery.LoadURL("http://www.example.com/feed?json")

Load JSON from string.

s :=`{
    "name":"John",
    "age":31,
    "city":"New York"
    }`
doc, err := jsonquery.Parse(strings.NewReader(s))

Load JSON from io.Reader.

f, err := os.Open("./books.json")
doc, err := jsonquery.Parse(f)

Parse JSON array

s := `[1,2,3,4,5,6]`
doc, _ := jsonquery.Parse(strings.NewReader(s))
list := jsonquery.Find(doc, "*")
for _, n := range list {
	fmt.Print(n.Value().(float64))
}

// Output: 1,2,3,4,5,6

Convert JSON object to XML

doc, _ := jsonquery.Parse(strings.NewReader(s))
fmt.Println(doc.OutputXML())

Methods

FindOne()

n := jsonquery.FindOne(doc,"//a")

Find()

list := jsonquery.Find(doc,"//a")

QuerySelector()

n := jsonquery.QuerySelector(doc, xpath.MustCompile("//a"))

QuerySelectorAll()

list :=jsonquery.QuerySelectorAll(doc, xpath.MustCompile("//a"))

Query()

n, err := jsonquery.Query(doc, "*")

QueryAll()

list, err := jsonquery.QueryAll(doc, "*")

Query() vs FindOne()

  • Query() will return an error if give xpath query expr is not valid.

  • FindOne will panic error and interrupt your program if give xpath query expr is not valid.

OutputXML()

Convert current JSON object to XML format.

Examples

{
  "store": {
    "book": [
      {
        "id": 1,
        "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      {
        "id": 2,
        "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      {
        "id": 3,
        "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      {
        "id": 4,
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  },
  "expensive": 10
}

Tests

Query Matched Native Value Types Native Values
//book 1 []interface{} {"book": [{"id":1,... }, {"id":2,... }, {"id":3,... }, {"id":4,... }]}
//book/* 4 [map[string]interface{}] {"id":1,... }, {"id":2,... }, {"id":3,... }, {"id":4,... }
//*[price<12.99] 2 [map[string]interface{}] {"id":1,...}, {"id":3,...}
//book/*/author 4 []string {"author": "Nigel Rees"}, {"author": "Evelyn Waugh"}, {"author": "Herman Melville"}, {"author": "J. R. R. Tolkien"}
//book/*[last()] 1 map[string]interface {} {"id":4,...}
//book/*[2] 1 map[string]interface{} {"id":2,...}
//*[isbn] 2 [map[string]interface{}] {"id":3,"isbn":"0-553-21311-3",...},{"id":4,"isbn":"0-395-19395-8",...}
//*[isbn='0-553-21311-3'] 1 map[string]interface{} {"id":3,"isbn":"0-553-21311-3",...}
//bicycle 1 map[string]interface {} {"bicycle":{"color":...,}}
//bicycle/color[text()='red'] 1 map[string]interface {} {"color":"red"}
//*/category[contains(.,'refer')] 1 string {"category": "reference"}
//price[.=22.99] 1 float64 {"price": 22.99}
//expensive/text() 1 string 10

For more supports XPath feature and function see https://github.com/antchfx/xpath




鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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