MCPcopy Create free account
hub / github.com/BlueSkyXN/AI2API / sanitizeJsonString

Function sanitizeJsonString

wo2api.go:982–1045  ·  view source on GitHub ↗

清理JSON字符串,去除可能导致JSON编码失败的字符

(input string, reqID string)

Source from the content-addressed store, hash-verified

980
981// 清理JSON字符串,去除可能导致JSON编码失败的字符
982func sanitizeJsonString(input string, reqID string) string {
983 if input == "" {
984 return input
985 }
986
987 // 记录原始长度
988 originalLen := len(input)
989
990 // 移除控制字符(除了常见的换行、回车、制表符)
991 cleanStr := strings.Map(func(r rune) rune {
992 if r < 32 && r != '\n' && r != '\r' && r != '\t' {
993 return -1 // 删除字符
994 }
995 return r
996 }, input)
997
998 // 处理不成对的引号和转义字符
999 var result strings.Builder
1000 inBackslash := false
1001 openQuote := false
1002
1003 for _, ch := range cleanStr {
1004 switch {
1005 case inBackslash:
1006 inBackslash = false
1007 result.WriteRune(ch)
1008 case ch == '\\':
1009 inBackslash = true
1010 result.WriteRune(ch)
1011 case ch == '"':
1012 openQuote = !openQuote
1013 result.WriteRune(ch)
1014 default:
1015 result.WriteRune(ch)
1016 }
1017 }
1018
1019 // 确保JSON合法性
1020 cleanedStr := result.String()
1021
1022 // 在关键位置添加额外日志,帮助排查问题
1023 if originalLen != len(cleanedStr) {
1024 logDebug("[reqID:%s] JSON清理: 原始长度=%d, 清理后长度=%d",
1025 reqID, originalLen, len(cleanedStr))
1026
1027 // 输出清理前后的部分样本用于比较
1028 sampleSize := 50
1029 if originalLen < sampleSize {
1030 sampleSize = originalLen
1031 }
1032
1033 logDebug("[reqID:%s] 清理前样本: %s", reqID, input[:sampleSize])
1034 if len(cleanedStr) < sampleSize {
1035 sampleSize = len(cleanedStr)
1036 }
1037
1038 if sampleSize > 0 {
1039 logDebug("[reqID:%s] 清理后样本: %s", reqID, cleanedStr[:sampleSize])

Callers 4

findMostLikelyContentFunction · 0.85
handleStreamingRequestFunction · 0.85

Calls 1

logDebugFunction · 0.70

Tested by

no test coverage detected