MCPcopy
hub / github.com/bitfield/script / JQ

Method JQ

script.go:725–760  ·  view source on GitHub ↗

JQ executes query on the pipe's contents (presumed to be valid JSON or [JSONLines] data), applying the query to each newline-delimited input value and producing results until the first error is encountered. An invalid query or value will set the appropriate error on the pipe. The exact dialect of J

(query string)

Source from the content-addressed store, hash-verified

723//
724// [JSONLines]: https://jsonlines.org/
725func (p *Pipe) JQ(query string) *Pipe {
726 parsedQuery, err := gojq.Parse(query)
727 if err != nil {
728 return p.WithError(err)
729 }
730 code, err := gojq.Compile(parsedQuery)
731 if err != nil {
732 return p.WithError(err)
733 }
734 return p.Filter(func(r io.Reader, w io.Writer) error {
735 dec := json.NewDecoder(r)
736 for dec.More() {
737 var input any
738 err := dec.Decode(&input)
739 if err != nil {
740 return err
741 }
742 iter := code.Run(input)
743 for {
744 v, ok := iter.Next()
745 if !ok {
746 break
747 }
748 if err, ok := v.(error); ok {
749 return err
750 }
751 result, err := gojq.Marshal(v)
752 if err != nil {
753 return err
754 }
755 fmt.Fprintln(w, string(result))
756 }
757 }
758 return nil
759 })
760}
761
762// Last produces only the last n lines of the pipe's contents, or all the lines
763// if there are less than n. If n is zero or negative, there is no output at

Calls 2

WithErrorMethod · 0.95
FilterMethod · 0.95