### Install jsonquery Go Package Source: https://github.com/antchfx/jsonquery/blob/master/README.md Provides the command to install the `jsonquery` library using Go's package manager. This is the initial step required to integrate the library into a Go project, allowing access to its JSON querying functionalities. ```Go go get github.com/antchfx/jsonquery ``` -------------------------------- ### Example JSON Input for Conversion Source: https://github.com/antchfx/jsonquery/blob/master/README.md This JSON object represents a sample data structure, including a store with books and a bicycle, and an additional 'expensive' field. It serves as the input for the JSON to XML conversion process. ```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 } ``` -------------------------------- ### Iterate JSON Object Child Nodes in Go Source: https://github.com/antchfx/jsonquery/blob/master/README.md Illustrates how to parse a JSON string into a `jsonquery.Document` and iterate over its top-level child nodes using `doc.ChildNodes()`. This example demonstrates accessing and printing the data and value of each node, providing a way to traverse the JSON structure programmatically. ```Go 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()) } } ``` -------------------------------- ### Load JSON Data in Go with jsonquery Source: https://github.com/antchfx/jsonquery/blob/master/README.md Provides various methods for loading JSON data into a `jsonquery.Document` object. This includes loading from a URL, directly from a string, and from an `io.Reader` (such as a file), demonstrating the flexibility of `jsonquery` in handling different JSON sources. ```Go doc, err := jsonquery.LoadURL("http://www.example.com/feed?json") ``` ```Go s :=`{ "name":"John", "age":31, "city":"New York" }` doc, err := jsonquery.Parse(strings.NewReader(s)) ``` ```Go f, err := os.Open("./books.json") doc, err := jsonquery.Parse(f) ``` -------------------------------- ### jsonquery Core Methods for Node Selection Source: https://github.com/antchfx/jsonquery/blob/master/README.md Documents the primary methods available in the `jsonquery` package for selecting nodes from a parsed JSON document using XPath expressions. It covers `FindOne` for single node selection, `Find` for multiple nodes, and `QuerySelector`/`QuerySelectorAll`/`Query`/`QueryAll` for more advanced or error-handling-aware queries. ```APIDOC jsonquery.FindOne(doc, xpathExpr string) *Node - Purpose: Finds the first node matching the given XPath expression. - Parameters: - doc: The *Document to query. - xpathExpr: The XPath expression string. - Returns: The first matching *Node, or nil if no match is found. - Note: Panics if the XPath expression is invalid. jsonquery.Find(doc, xpathExpr string) []*Node - Purpose: Finds all nodes matching the given XPath expression. - Parameters: - doc: The *Document to query. - xpathExpr: The XPath expression string. - Returns: A slice of matching *Node pointers, or an empty slice if no matches. jsonquery.QuerySelector(doc, expr *xpath.Expr) *Node - Purpose: Finds the first node matching a pre-compiled XPath expression. - Parameters: - doc: The *Document to query. - expr: A pre-compiled *xpath.Expr object. - Returns: The first matching *Node, or nil. jsonquery.QuerySelectorAll(doc, expr *xpath.Expr) []*Node - Purpose: Finds all nodes matching a pre-compiled XPath expression. - Parameters: - doc: The *Document to query. - expr: A pre-compiled *xpath.Expr object. - Returns: A slice of matching *Node pointers, or an empty slice. jsonquery.Query(doc, xpathExpr string) (*Node, error) - Purpose: Finds the first node matching the given XPath expression, returning an error for invalid expressions. - Parameters: - doc: The *Document to query. - xpathExpr: The XPath expression string. - Returns: The first matching *Node and an error if the expression is invalid or an issue occurs. - Note: Prefer this over FindOne() for error handling. jsonquery.QueryAll(doc, xpathExpr string) ([]*Node, error) - Purpose: Finds all nodes matching the given XPath expression, returning an error for invalid expressions. - Parameters: - doc: The *Document to query. - xpathExpr: The XPath expression string. - Returns: A slice of matching *Node pointers and an error if the expression is invalid or an issue occurs. Document.OutputXML() string - Purpose: Converts the current JSON object (Document) to its XML string representation. - Parameters: None. - Returns: A string containing the XML representation of the JSON document. ``` -------------------------------- ### Go Code to Convert JSON to XML using jsonquery Source: https://github.com/antchfx/jsonquery/blob/master/README.md This Go snippet demonstrates how to parse a JSON string using `jsonquery.Parse` and then convert the parsed document into an XML string using `doc.OutputXML()`. It handles potential parsing errors, showcasing a common pattern for data transformation. ```go doc, err := jsonquery.Parse(strings.NewReader(s)) if err != nil { panic(err) } fmt.Println(doc.OutputXML()) ``` -------------------------------- ### Parse and Iterate JSON Array in Go Source: https://github.com/antchfx/jsonquery/blob/master/README.md Demonstrates how to parse a JSON array string and iterate over its elements using `jsonquery.Find`. It shows how to extract individual numeric values from the array, highlighting `jsonquery`'s capability to handle root-level JSON arrays. ```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)) } ``` -------------------------------- ### Select the second book entry Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects the second direct child element of any 'book' element. It uses positional indexing to access a specific item within a collection. ```XPath //book/*[2] ``` -------------------------------- ### Select price equal to 22.99 Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects any 'price' element whose value is exactly 22.99. It demonstrates direct numerical equality comparison for element values. ```XPath //price[.=22.99] ``` -------------------------------- ### Select elements with price less than 12.99 Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects any element that has a 'price' child element with a value less than 12.99. It demonstrates filtering based on numerical comparison across all elements in the document. ```XPath //*[price<12.99] ``` -------------------------------- ### Select all book elements Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects all elements named 'book' anywhere in the document. It demonstrates a basic descendant-or-self axis selection to retrieve all occurrences of a specific element type. ```XPath //book ``` -------------------------------- ### Resulting XML Output from JSON Conversion Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XML structure is the expected output after converting the provided JSON input using the `jsonquery` library in Go. It illustrates how the JSON fields are mapped to XML elements, maintaining the hierarchical structure of the original data. ```xml 10 red 19.95 Nigel Rees reference 1 8.95 Sayings of the Century Evelyn Waugh fiction 2 12.99 Sword of Honour Herman Melville fiction 3 0-553-21311-3 8.99 Moby Dick J. R. R. Tolkien fiction 4 0-395-19395-8 22.99 The Lord of the Rings ``` -------------------------------- ### Extract Data from JSON using XPath in Go Source: https://github.com/antchfx/jsonquery/blob/master/README.md Demonstrates how to parse a JSON string into a `jsonquery.Document` and extract specific values using XPath expressions with `jsonquery.FindOne`. It illustrates accessing nested fields and array elements, showcasing the flexibility of XPath for JSON data retrieval without predefined Go structs. ```Go 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" } ``` -------------------------------- ### Select author of all book entries Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects the 'author' element for every direct child of a 'book' element. It's used to extract specific nested information from a collection of items. ```XPath //book/*/author ``` -------------------------------- ### Select the bicycle element Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects the 'bicycle' element anywhere in the document. It's a straightforward selection of a specific element by its name. ```XPath //bicycle ``` -------------------------------- ### Select all direct children of book elements Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects all direct child elements of any 'book' element. It's useful for retrieving individual book entries or their top-level properties within the JSON structure. ```XPath //book/* ``` -------------------------------- ### Select bicycle color if red Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects the 'color' element within a 'bicycle' element, specifically when its text content is 'red'. It combines element selection with text content filtering. ```XPath //bicycle/color[text()='red'] ``` -------------------------------- ### Select the last book entry Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects the last direct child element of any 'book' element. It uses the `last()` function to retrieve the final item in a sequence. ```XPath //book/*[last()] ``` -------------------------------- ### Select elements that have an ISBN Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects any element that contains an 'isbn' child element. It's useful for identifying items based on the presence of a specific property. ```XPath //*[isbn] ``` -------------------------------- ### Convert JSON Object to XML Format in Go Source: https://github.com/antchfx/jsonquery/blob/master/README.md Illustrates how to parse a JSON string containing an array of objects and convert it into an XML string using the `doc.OutputXML()` method. This functionality allows for easy transformation of JSON data into an XML representation. ```Go s := `[{"name":"John", "age":31, "female":false, "city":null}]` doc, _ := jsonquery.Parse(strings.NewReader(s)) fmt.Println(doc.OutputXML()) ``` -------------------------------- ### Select category containing 'refer' Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects any 'category' element whose text content contains the substring 'refer'. It uses the `contains()` function for partial string matching. ```XPath //*/category[contains(.,'refer')] ``` -------------------------------- ### Select elements with a specific ISBN Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects any element that has an 'isbn' child element with the exact value '0-553-21311-3'. It demonstrates filtering based on a specific attribute value. ```XPath //*[isbn='0-553-21311-3'] ``` -------------------------------- ### Extract text content of expensive element Source: https://github.com/antchfx/jsonquery/blob/master/README.md This XPath query selects the text content of the 'expensive' element. It's used to retrieve the scalar value directly associated with an element. ```XPath //expensive/text() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.