1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
|
# jsonquery
[](https://github.com/antchfx/jsonquery/actions/workflows/testing.yml)
[](https://godoc.org/github.com/antchfx/jsonquery)
[](https://goreportcard.com/report/github.com/antchfx/jsonquery)
# Overview
[jsonquery](https://github.com/antchfx/jsonquery) is XPath query package for JSON document depended on [xpath](https://github.com/antchfx/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](https://github.com/antchfx/htmlquery) - XPath query package for HTML document
- [xmlquery](https://github.com/antchfx/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 structure or using regexp to extract some data in JSON file, gets any data is easy and fast in jsonquery now.
Using an xpath like syntax to access specific fields of a json structure.
```go
// https://go.dev/play/p/vqoD_jWryKY
package main
import (
"fmt"
"strings"
"github.com/antchfx/jsonquery"
)
func main() {
s := `{
"person":{
"name":"John",
"age":31,
"female":false,
"city":null,
"hobbies":[
"coding",
"eating",
"football"
]
}
}`
doc, err := jsonquery.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
// xpath query
age := jsonquery.FindOne(doc, "age")
// or
age = jsonquery.FindOne(doc, "person/age")
fmt.Printf("%#v[%T]\n", age.Value(), age.Value()) // prints 31[float64]
hobbies := jsonquery.FindOne(doc, "//hobbies")
fmt.Printf("%#v\n", hobbies.Value()) // prints []interface {}{"coding", "eating", "football"}
firstHobby := jsonquery.FindOne(doc, "//hobbies/*[1]")
fmt.Printf("%#v\n", firstHobby.Value()) // "coding"
}
```
Iterating over a json structure.
```go
// https://go.dev/play/p/vwXQKTCLdVK
package main
import (
"fmt"
"strings"
"github.com/antchfx/jsonquery"
)
func main() {
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())
}
}
```
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.
```go
doc, err := jsonquery.LoadURL("http://www.example.com/feed?json")
```
#### Load JSON from string.
```go
s :=`{
"name":"John",
"age":31,
"city":"New York"
}`
doc, err := jsonquery.Parse(strings.NewReader(s))
```
#### Load JSON from io.Reader.
```go
f, err := os.Open("./books.json")
doc, err := jsonquery.Parse(f)
```
#### Parse JSON array
```go
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 file
```go
s := `[{"name":"John", "age":31, "female":false, "city":null}]`
doc, _ := jsonquery.Parse(strings.NewReader(s))
fmt.Println(doc.OutputXML())
```
### Methods
#### FindOne()
```go
n := jsonquery.FindOne(doc,"//a")
```
#### Find()
```go
list := jsonquery.Find(doc,"//a")
```
#### QuerySelector()
```go
n := jsonquery.QuerySelector(doc, xpath.MustCompile("//a"))
```
#### QuerySelectorAll()
```go
list :=jsonquery.QuerySelectorAll(doc, xpath.MustCompile("//a"))
```
#### Query()
```go
n, err := jsonquery.Query(doc, "*")
```
#### QueryAll()
```go
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.
## Example of how to convert JSON object to XML file
```json
{
"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
}
```
```go
doc, err := jsonquery.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
fmt.Println(doc.OutputXML())
```
Output the below XML:
```xml
<?xml version="1.0" encoding="utf-8"?>
<root>
<expensive>10</expensive>
<store>
<bicycle>
<color>red</color>
<price>19.95</price>
</bicycle>
<book>
<author>Nigel Rees</author>
<category>reference</category>
<id>1</id>
<price>8.95</price>
<title>Sayings of the Century</title>
</book>
<book>
<author>Evelyn Waugh</author>
<category>fiction</category>
<id>2</id>
<price>12.99</price>
<title>Sword of Honour</title>
</book>
<book>
<author>Herman Melville</author>
<category>fiction</category>
<id>3</id>
<isbn>0-553-21311-3</isbn>
<price>8.99</price>
<title>Moby Dick</title>
</book>
<book>
<author>J. R. R. Tolkien</author>
<category>fiction</category>
<id>4</id>
<isbn>0-395-19395-8</isbn>
<price>22.99</price>
<title>The Lord of the Rings</title>
</book>
</store>
</root>
```
## XPath 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
|