{"id":13694311,"url":"https://github.com/antchfx/jsonquery","last_synced_at":"2025-05-03T01:32:23.939Z","repository":{"id":43075664,"uuid":"134059049","full_name":"antchfx/jsonquery","owner":"antchfx","description":"JSON xpath query for Go. Golang XPath query for JSON query.","archived":false,"fork":false,"pushed_at":"2024-06-24T04:05:01.000Z","size":53,"stargazers_count":251,"open_issues_count":3,"forks_count":29,"subscribers_count":7,"default_branch":"master","last_synced_at":"2024-08-03T17:19:33.965Z","etag":null,"topics":["golang","jsonpath","jsonpath-query","jsonq","jsonquery","xpath"],"latest_commit_sha":null,"homepage":"https://github.com/antchfx/xpath","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/antchfx.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-05-19T12:16:34.000Z","updated_at":"2024-07-16T07:37:56.000Z","dependencies_parsed_at":"2024-01-13T23:08:19.456Z","dependency_job_id":"8d144c93-205d-4372-b107-cfcd937f0cc7","html_url":"https://github.com/antchfx/jsonquery","commit_stats":null,"previous_names":[],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/antchfx%2Fjsonquery","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/antchfx%2Fjsonquery/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/antchfx%2Fjsonquery/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/antchfx%2Fjsonquery/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/antchfx","download_url":"https://codeload.github.com/antchfx/jsonquery/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224346486,"owners_count":17296221,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["golang","jsonpath","jsonpath-query","jsonq","jsonquery","xpath"],"created_at":"2024-08-02T17:01:29.105Z","updated_at":"2024-11-12T20:31:58.724Z","avatar_url":"https://github.com/antchfx.png","language":"Go","readme":"# jsonquery\n\n[![Build Status](https://github.com/antchfx/jsonquery/actions/workflows/testing.yml/badge.svg)](https://github.com/antchfx/jsonquery/actions/workflows/testing.yml)\n[![GoDoc](https://godoc.org/github.com/antchfx/jsonquery?status.svg)](https://godoc.org/github.com/antchfx/jsonquery)\n[![Go Report Card](https://goreportcard.com/badge/github.com/antchfx/jsonquery)](https://goreportcard.com/report/github.com/antchfx/jsonquery)\n\n# Overview\n\n[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.\n\njsonquery 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.\n\n- [htmlquery](https://github.com/antchfx/htmlquery) - XPath query package for HTML document\n\n- [xmlquery](https://github.com/antchfx/xmlquery) - XPath query package for XML document.\n\n### Install Package\n\n```\ngo get github.com/antchfx/jsonquery\n```\n\n## Get Started\n\nThe 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.\n\nUsing an xpath like syntax to access specific fields of a json structure.\n\n```go\n// https://go.dev/play/p/vqoD_jWryKY\npackage main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/antchfx/jsonquery\"\n)\n\nfunc main() {\n\ts := `{\n            \"person\":{\n               \"name\":\"John\",\n               \"age\":31,\n               \"female\":false,\n               \"city\":null,\n               \"hobbies\":[\n                  \"coding\",\n                  \"eating\",\n                  \"football\"\n               ]\n            }\n         }`\n\tdoc, err := jsonquery.Parse(strings.NewReader(s))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// xpath query\n\tage := jsonquery.FindOne(doc, \"age\")\n\t// or\n\tage = jsonquery.FindOne(doc, \"person/age\")\n\tfmt.Printf(\"%#v[%T]\\n\", age.Value(), age.Value()) // prints 31[float64]\n\n\thobbies := jsonquery.FindOne(doc, \"//hobbies\")\n\tfmt.Printf(\"%#v\\n\", hobbies.Value()) // prints []interface {}{\"coding\", \"eating\", \"football\"}\n\tfirstHobby := jsonquery.FindOne(doc, \"//hobbies/*[1]\")\n\tfmt.Printf(\"%#v\\n\", firstHobby.Value()) // \"coding\"\n}\n```\n\nIterating over a json structure.\n\n```go\n// https://go.dev/play/p/vwXQKTCLdVK\npackage main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/antchfx/jsonquery\"\n)\n\nfunc main() {\n\ts := `{\n\t\"name\":\"John\",\n\t\"age\":31,\n\t\"female\":false,\n\t\"city\":null\n\t}`\n\tdoc, err := jsonquery.Parse(strings.NewReader(s))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// iterate all json objects from child ndoes.\n\tfor _, n := range doc.ChildNodes() {\n\t\tfmt.Printf(\"%s: %v[%T]\\n\", n.Data, n.Value(), n.Value())\n\t}\n}\n```\n\nOutput:\n\n```\nname: John[string]\nage: 31[float64]\nfemale: false[bool]\ncity: \u003cnil\u003e[\u003cnil\u003e]\n```\n\nThe default Json types and Go types are:\n\n| JSON    | jsonquery(go) |\n| ------- | ------------- |\n| object  | interface{}   |\n| string  | string        |\n| number  | float64       |\n| boolean | bool          |\n| array   | []interface{} |\n| null    | nil           |\n\nFor more information about JSON \u0026 Go see the https://go.dev/blog/json\n\n## Getting Started\n\n#### Load JSON from URL.\n\n```go\ndoc, err := jsonquery.LoadURL(\"http://www.example.com/feed?json\")\n```\n\n#### Load JSON from string.\n\n```go\ns :=`{\n    \"name\":\"John\",\n    \"age\":31,\n    \"city\":\"New York\"\n    }`\ndoc, err := jsonquery.Parse(strings.NewReader(s))\n```\n\n#### Load JSON from io.Reader.\n\n```go\nf, err := os.Open(\"./books.json\")\ndoc, err := jsonquery.Parse(f)\n```\n\n#### Parse JSON array\n\n```go\ns := `[1,2,3,4,5,6]`\ndoc, _ := jsonquery.Parse(strings.NewReader(s))\nlist := jsonquery.Find(doc, \"*\")\nfor _, n := range list {\n\tfmt.Print(n.Value().(float64))\n}\n```\n\n// Output: `1,2,3,4,5,6`\n\n#### Convert JSON object to XML file\n\n```go\ns := `[{\"name\":\"John\", \"age\":31, \"female\":false, \"city\":null}]`\ndoc, _ := jsonquery.Parse(strings.NewReader(s))\nfmt.Println(doc.OutputXML())\n```\n\n### Methods\n\n#### FindOne()\n\n```go\nn := jsonquery.FindOne(doc,\"//a\")\n```\n\n#### Find()\n\n```go\nlist := jsonquery.Find(doc,\"//a\")\n```\n\n#### QuerySelector()\n\n```go\nn := jsonquery.QuerySelector(doc, xpath.MustCompile(\"//a\"))\n```\n\n#### QuerySelectorAll()\n\n```go\nlist :=jsonquery.QuerySelectorAll(doc, xpath.MustCompile(\"//a\"))\n```\n\n#### Query()\n\n```go\nn, err := jsonquery.Query(doc, \"*\")\n```\n\n#### QueryAll()\n\n```go\nlist, err := jsonquery.QueryAll(doc, \"*\")\n```\n\n#### Query() vs FindOne()\n\n- `Query()` will return an error if give xpath query expr is not valid.\n\n- `FindOne` will panic error and interrupt your program if give xpath query expr is not valid.\n\n#### OutputXML()\n\nConvert current JSON object to XML format.\n\n## Example of how to convert JSON object to XML file\n\n```json\n{\n  \"store\": {\n    \"book\": [\n      {\n        \"id\": 1,\n        \"category\": \"reference\",\n        \"author\": \"Nigel Rees\",\n        \"title\": \"Sayings of the Century\",\n        \"price\": 8.95\n      },\n      {\n        \"id\": 2,\n        \"category\": \"fiction\",\n        \"author\": \"Evelyn Waugh\",\n        \"title\": \"Sword of Honour\",\n        \"price\": 12.99\n      },\n      {\n        \"id\": 3,\n        \"category\": \"fiction\",\n        \"author\": \"Herman Melville\",\n        \"title\": \"Moby Dick\",\n        \"isbn\": \"0-553-21311-3\",\n        \"price\": 8.99\n      },\n      {\n        \"id\": 4,\n        \"category\": \"fiction\",\n        \"author\": \"J. R. R. Tolkien\",\n        \"title\": \"The Lord of the Rings\",\n        \"isbn\": \"0-395-19395-8\",\n        \"price\": 22.99\n      }\n    ],\n    \"bicycle\": {\n      \"color\": \"red\",\n      \"price\": 19.95\n    }\n  },\n  \"expensive\": 10\n}\n```\n\n```go\ndoc, err := jsonquery.Parse(strings.NewReader(s))\nif err != nil {\n\tpanic(err)\n}\nfmt.Println(doc.OutputXML())\n```\n\nOutput the below XML:\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003croot\u003e\n  \u003cexpensive\u003e10\u003c/expensive\u003e\n  \u003cstore\u003e\n    \u003cbicycle\u003e\n      \u003ccolor\u003ered\u003c/color\u003e\n      \u003cprice\u003e19.95\u003c/price\u003e\n    \u003c/bicycle\u003e\n    \u003cbook\u003e\n      \u003cauthor\u003eNigel Rees\u003c/author\u003e\n      \u003ccategory\u003ereference\u003c/category\u003e\n      \u003cid\u003e1\u003c/id\u003e\n      \u003cprice\u003e8.95\u003c/price\u003e\n      \u003ctitle\u003eSayings of the Century\u003c/title\u003e\n    \u003c/book\u003e\n    \u003cbook\u003e\n      \u003cauthor\u003eEvelyn Waugh\u003c/author\u003e\n      \u003ccategory\u003efiction\u003c/category\u003e\n      \u003cid\u003e2\u003c/id\u003e\n      \u003cprice\u003e12.99\u003c/price\u003e\n      \u003ctitle\u003eSword of Honour\u003c/title\u003e\n    \u003c/book\u003e\n    \u003cbook\u003e\n      \u003cauthor\u003eHerman Melville\u003c/author\u003e\n      \u003ccategory\u003efiction\u003c/category\u003e\n      \u003cid\u003e3\u003c/id\u003e\n      \u003cisbn\u003e0-553-21311-3\u003c/isbn\u003e\n      \u003cprice\u003e8.99\u003c/price\u003e\n      \u003ctitle\u003eMoby Dick\u003c/title\u003e\n    \u003c/book\u003e\n    \u003cbook\u003e\n      \u003cauthor\u003eJ. R. R. Tolkien\u003c/author\u003e\n      \u003ccategory\u003efiction\u003c/category\u003e\n      \u003cid\u003e4\u003c/id\u003e\n      \u003cisbn\u003e0-395-19395-8\u003c/isbn\u003e\n      \u003cprice\u003e22.99\u003c/price\u003e\n      \u003ctitle\u003eThe Lord of the Rings\u003c/title\u003e\n    \u003c/book\u003e\n  \u003c/store\u003e\n\u003c/root\u003e\n```\n\n## XPath Tests\n\n| Query                               | Matched | Native Value Types       | Native Values                                                                                                               |\n| ----------------------------------- | ------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------- |\n| `//book`                            | 1       | []interface{}            | `{\"book\": [{\"id\":1,... }, {\"id\":2,... }, {\"id\":3,... }, {\"id\":4,... }]}`                                                    |\n| `//book/*`                          | 4       | [map[string]interface{}] | `{\"id\":1,... }`, `{\"id\":2,... }`, `{\"id\":3,... }`, `{\"id\":4,... }`                                                          |\n| `//*[price\u003c12.99]`                  | 2       | [map[string]interface{}] | `{\"id\":1,...}`, `{\"id\":3,...}`                                                                                              |\n| `//book/*/author`                   | 4       | []string                 | `{\"author\": \"Nigel Rees\"}`, `{\"author\": \"Evelyn Waugh\"}`, `{\"author\": \"Herman Melville\"}`, `{\"author\": \"J. R. R. Tolkien\"}` |\n| `//book/*[last()]`                  | 1       | map[string]interface {}  | `{\"id\":4,...}`                                                                                                              |\n| `//book/*[2]`                       | 1       | map[string]interface{}   | `{\"id\":2,...}`                                                                                                              |\n| `//*[isbn]`                         | 2       | [map[string]interface{}] | `{\"id\":3,\"isbn\":\"0-553-21311-3\",...}`,`{\"id\":4,\"isbn\":\"0-395-19395-8\",...}`                                                 |\n| `//*[isbn='0-553-21311-3']`         | 1       | map[string]interface{}   | `{\"id\":3,\"isbn\":\"0-553-21311-3\",...}`                                                                                       |\n| `//bicycle`                         | 1       | map[string]interface {}  | `{\"bicycle\":{\"color\":...,}}`                                                                                                |\n| `//bicycle/color[text()='red']`     | 1       | map[string]interface {}  | `{\"color\":\"red\"}`                                                                                                           |\n| `//*/category[contains(.,'refer')]` | 1       | string                   | `{\"category\": \"reference\"}`                                                                                                 |\n| `//price[.=22.99]`                  | 1       | float64                  | `{\"price\": 22.99}`                                                                                                          |\n| `//expensive/text()`                | 1       | string                   | `10`                                                                                                                        |\n\nFor more supports XPath feature and function see https://github.com/antchfx/xpath\n","funding_links":[],"categories":["开源类库","Open source library","Go"],"sub_categories":["JSON"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fantchfx%2Fjsonquery","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fantchfx%2Fjsonquery","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fantchfx%2Fjsonquery/lists"}