log / identify specific value of JSON using JSON pointer
We can parse a JSON using JSON Pointer. JSON Pointer is a standardized approach to accessing particular data within a JSON document based on IETF RFC6901. For example, if we have a JSON object representing a collection of books,
[
{"title": "The Go Programming Language", "author": "Alan A. A. Donovan"},
{"title": "Learning Go", "author": "Miek Gieben"}
]
a JSON Pointer like /books/0/title would fetch the title of the first book in the array.
Here’s an example of JSON Pointer in Go:
package main
import (
"encoding/json"
"fmt"
"github.com/qri-io/jsonpointer"
)
func main() {
// Define the JSON document
doc := `{
"books": [
{"title": "The Go Programming Language", "author": "Alan A. A. Donovan"},
{"title": "Learning Go", "author": "Miek Gieben"}
]
}`
// Unmarshal the JSON document into an interface{}
var data map[string]interface{}
json.Unmarshal([]byte(doc), &data)
// Define the JSON Pointer
ptr, _ := jsonpointer.Parse("/books/0/title")
// evaluate the pointer against the document
// evaluation always starts at the root of the document
got, _ := ptr.Eval(data)
// Print the extracted value
fmt.Printf("The title of the first book is: %s\n", got)
}
In this example, the ptr.Eval(data) function extracts the title of the first book in the books array by utilizing the JSON Pointer /books/0/title. By employing json.Unmarshal, the JSON document is parsed into a data structure that can be navigated with the JSON Pointer.