2
0
mirror of https://github.com/jmespath/jp synced 2025-08-22 09:37:10 +00:00
jp/jp.go

84 lines
1.9 KiB
Go
Raw Normal View History

2015-08-09 17:44:46 -07:00
package main
import (
"encoding/json"
"fmt"
"os"
2015-08-10 22:46:39 -07:00
"github.com/jmespath/jp/Godeps/_workspace/src/github.com/codegangsta/cli"
"github.com/jmespath/jp/Godeps/_workspace/src/github.com/jmespath/go-jmespath"
2015-08-09 17:44:46 -07:00
)
func main() {
app := cli.NewApp()
app.Name = "jp"
2015-08-12 22:09:59 -07:00
app.Version = "0.0.3"
2015-08-09 20:51:01 -07:00
app.Usage = "jp [<options>] <expression>"
2015-08-09 17:44:46 -07:00
app.Author = ""
app.Email = ""
2015-08-09 20:51:01 -07:00
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "filename, f",
Usage: "Read input JSON from a file instead of stdin.",
},
cli.BoolFlag{
Name: "unquoted, u",
Usage: "If the final result is a string, it will be printed without quotes.",
EnvVar: "JP_UNQUOTED",
},
}
2015-08-09 17:44:46 -07:00
app.Action = runMainAndExit
app.Run(os.Args)
}
func runMainAndExit(c *cli.Context) {
os.Exit(runMain(c))
}
func runMain(c *cli.Context) int {
if len(c.Args()) == 0 {
fmt.Fprintf(os.Stderr, "Must provide at least one argument.\n")
return 255
}
expression := c.Args()[0]
var input interface{}
2015-08-09 20:51:01 -07:00
var jsonParser *json.Decoder
if c.String("filename") != "" {
f, err := os.Open(c.String("filename"))
if err != nil {
fmt.Fprintf(os.Stderr, "Error opening input file: %s\n", err)
return 1
}
jsonParser = json.NewDecoder(f)
} else {
jsonParser = json.NewDecoder(os.Stdin)
}
jsonParser.UseNumber()
2015-08-09 17:44:46 -07:00
if err := jsonParser.Decode(&input); err != nil {
fmt.Fprintf(os.Stderr, "Error parsing input json: %s\n", err)
return 2
}
result, err := jmespath.Search(expression, input)
if err != nil {
fmt.Fprintf(os.Stderr,
"Error evaluating JMESPath expression: %s\n", err)
return 1
}
2015-08-09 20:51:01 -07:00
converted, isString := result.(string)
if c.Bool("unquoted") && isString {
os.Stdout.WriteString(converted)
} else {
toJSON, err := json.MarshalIndent(result, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr,
"Error marshalling result to JSON: %s\n", err)
return 3
}
os.Stdout.Write(toJSON)
2015-08-09 17:44:46 -07:00
}
os.Stdout.WriteString("\n")
return 0
}