github.com/galdor/go-ejson@v0.0.0-20231201100034-d335379f26b0/cmd/json-pointer/main.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"os"
     6  
     7  	jsonpointer "github.com/galdor/go-ejson"
     8  	"github.com/galdor/go-program"
     9  )
    10  
    11  func main() {
    12  	var c *program.Command
    13  
    14  	p := program.NewProgram("json-pointer",
    15  		"example of JSON pointer manipulation")
    16  
    17  	c = p.AddCommand("find",
    18  		"extract and print the json value referenced by a pointer", cmdFind)
    19  	c.AddArgument("pointer", "the json pointer")
    20  	c.AddOptionalArgument("path", "the file containing the json document")
    21  
    22  	p.ParseCommandLine()
    23  	p.Run()
    24  }
    25  
    26  func cmdFind(p *program.Program) {
    27  	pointerString := p.ArgumentValue("pointer")
    28  	var pointer jsonpointer.Pointer
    29  	if err := pointer.Parse(pointerString); err != nil {
    30  		p.Fatal("invalid json pointer: %v", err)
    31  	}
    32  
    33  	filePath := p.ArgumentValue("path")
    34  	var file *os.File
    35  	if filePath == "" {
    36  		file = os.Stdin
    37  	} else {
    38  		var err error
    39  		file, err = os.Open(filePath)
    40  		if err != nil {
    41  			p.Fatal("cannot open %q: %v", filePath, err)
    42  		}
    43  	}
    44  	defer file.Close()
    45  
    46  	decoder := json.NewDecoder(file)
    47  	var document interface{}
    48  	if err := decoder.Decode(&document); err != nil {
    49  		p.Fatal("cannot parse json data: %v", err)
    50  	}
    51  
    52  	value := pointer.Find(document)
    53  
    54  	encoder := json.NewEncoder(os.Stdout)
    55  	encoder.SetIndent("", "  ")
    56  
    57  	if err := encoder.Encode(value); err != nil {
    58  		p.Fatal("cannot serialize json value: %v", err)
    59  	}
    60  }