MCPcopy
hub / github.com/keploy/keploy / jsonEscapeString

Function jsonEscapeString

utils/utils.go:1507–1528  ·  view source on GitHub ↗

jsonEscapeString returns a JSON-safe representation of s suitable for embedding directly inside a JSON string literal. It escapes characters that must not appear unescaped in JSON strings (newlines, quotes, etc.) but does not add surrounding quotes.

(logger *zap.Logger, s string)

Source from the content-addressed store, hash-verified

1505// that must not appear unescaped in JSON strings (newlines, quotes, etc.)
1506// but does not add surrounding quotes.
1507func jsonEscapeString(logger *zap.Logger, s string) string {
1508 if s == "" {
1509 return ""
1510 }
1511 b, err := json.Marshal(s)
1512 // json.Marshal on a string should rarely fail, but if it does, log it
1513 // and return the original string to avoid breaking the flow.
1514 if err != nil {
1515 LogError(logger, err, "failed to marshal string for JSON escaping, returning original unescaped string", zap.String("string", s))
1516 return s
1517 }
1518
1519 // The result of marshaling a string is a JSON string literal, which includes
1520 // surrounding quotes. We need to strip them.
1521 if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
1522 // This case is highly unlikely if json.Marshal succeeded without error.
1523 LogError(logger, fmt.Errorf("json.Marshal returned unexpected format: %s", string(b)), "unexpected output from json.Marshal for a string", zap.String("string", s))
1524 return s
1525 }
1526 // Strip the surrounding quotes added by json.Marshal.
1527 return string(b[1 : len(b)-1])
1528}
1529
1530// // XMLToMap converts an XML string into a map[string]interface{}
1531// func XMLToMap(data string) (map[string]any, error) {

Callers 1

RenderTemplatesInStringFunction · 0.85

Calls 3

LogErrorFunction · 0.85
MarshalMethod · 0.80
StringMethod · 0.45

Tested by

no test coverage detected