File: json.go

package info (click to toggle)
wuzz 0.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 372 kB
  • sloc: makefile: 6
file content (53 lines) | stat: -rw-r--r-- 1,259 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package formatter

import (
	"bytes"
	"errors"
	"io"

	"github.com/nwidger/jsoncolor"
	"github.com/tidwall/gjson"
)

type jsonFormatter struct {
	parsedBody gjson.Result
	TextFormatter
}

func (f *jsonFormatter) Format(writer io.Writer, data []byte) error {
	jsonFormatter := jsoncolor.NewFormatter()
	buf := bytes.NewBuffer(make([]byte, 0, len(data)))
	err := jsonFormatter.Format(buf, data)
	if err == nil {
		writer.Write(buf.Bytes())
		return nil
	}
	return errors.New("json formatter error")
}

func (f *jsonFormatter) Title() string {
	return "[json]"
}

func (f *jsonFormatter) Search(q string, body []byte) ([]string, error) {
	if q != "" {
		if f.parsedBody.Type != gjson.JSON {
			f.parsedBody = gjson.ParseBytes(body)
		}
		searchResult := f.parsedBody.Get(q)
		if searchResult.Type == gjson.Null {
			return nil, errors.New("Invalid gjson query or no results found")
		}
		if searchResult.Type != gjson.JSON {
			return []string{searchResult.String()}, nil
		}
		body = []byte(searchResult.String())
	}
	jsonFormatter := jsoncolor.NewFormatter()
	buf := bytes.NewBuffer(make([]byte, 0, len(body)))
	err := jsonFormatter.Format(buf, body)
	if err != nil {
		return nil, errors.New("Invalid results")
	}
	return []string{string(buf.Bytes())}, nil
}