MCPcopy Index your code
hub / github.com/keploy/keploy / sanitizeTemplatedJSON

Function sanitizeTemplatedJSON

pkg/util.go:3736–3789  ·  view source on GitHub ↗

sanitizeTemplatedJSON makes a JSON string containing go-template placeholders parseable by wrapping any placeholder tokens that appear in value positions without surrounding quotes with quotes. Example: {"arr":[{{int .a}},{{int .b}}]} => {"arr":["{{int .a}}","{{int .b}}"]} This lets us unmarshal whi

(raw string, placeholderRe *regexp.Regexp)

Source from the content-addressed store, hash-verified

3734// Example: {"arr":[{{int .a}},{{int .b}}]} => {"arr":["{{int .a}}","{{int .b}}"]}
3735// This lets us unmarshal while still preserving the placeholder text for later extraction.
3736func sanitizeTemplatedJSON(raw string, placeholderRe *regexp.Regexp) string {
3737 if raw == "" {
3738 return raw
3739 }
3740 // Precompute which byte positions are inside JSON string literals.
3741 inString := make([]bool, len(raw))
3742 escaped := false
3743 inside := false
3744 for i := 0; i < len(raw); i++ {
3745 c := raw[i]
3746 if c == '\\' && !escaped { // potential escape for next char
3747 escaped = true
3748 if inside {
3749 inString[i] = true
3750 }
3751 continue
3752 }
3753 if c == '"' && !escaped { // toggle string state
3754 inside = !inside
3755 inString[i] = inside
3756 continue
3757 }
3758 if inside {
3759 inString[i] = true
3760 }
3761 escaped = false
3762 }
3763
3764 matches := placeholderRe.FindAllStringIndex(raw, -1)
3765 if len(matches) == 0 {
3766 return raw
3767 }
3768
3769 // Build sanitized output.
3770 var b strings.Builder
3771 last := 0
3772 for _, m := range matches {
3773 start, end := m[0], m[1]
3774 // Determine if this placeholder starts inside a string literal.
3775 insideString := start < len(inString) && inString[start]
3776 b.WriteString(raw[last:start])
3777 if !insideString {
3778 // Insert quotes to force valid JSON token.
3779 b.WriteByte('"')
3780 b.WriteString(raw[start:end])
3781 b.WriteByte('"')
3782 } else {
3783 b.WriteString(raw[start:end])
3784 }
3785 last = end
3786 }
3787 b.WriteString(raw[last:])
3788 return b.String()
3789}
3790
3791// LooksLikeJSON checks if a string appears to be JSON by checking for opening and closing brackets/braces.
3792// It trims whitespace and returns false for empty strings.

Callers 1

Calls 1

StringMethod · 0.45

Tested by

no test coverage detected