@@ -16,6 +16,10 @@ import (
1616
1717var encoders sync.Map // map[encoderEntry]encoderFunc
1818
19+ // If we want to set a literal key value into JSON using sjson, we need to make sure it doesn't have
20+ // special characters that sjson interprets as a path.
21+ var EscapeSJSONKey = strings .NewReplacer ("\\ " , "\\ \\ " , "|" , "\\ |" , "#" , "\\ #" , "@" , "\\ @" , "*" , "\\ *" , "." , "\\ ." , ":" , "\\ :" , "?" , "\\ ?" ).Replace
22+
1923func Marshal (value any ) ([]byte , error ) {
2024 e := & encoder {dateFormat : time .RFC3339 }
2125 return e .marshal (value )
@@ -270,7 +274,7 @@ func (e *encoder) newStructTypeEncoder(t reflect.Type) encoderFunc {
270274 if encoded == nil {
271275 continue
272276 }
273- json , err = sjson .SetRawBytes (json , ef .tag .name , encoded )
277+ json , err = sjson .SetRawBytes (json , EscapeSJSONKey ( ef .tag .name ) , encoded )
274278 if err != nil {
275279 return nil , err
276280 }
@@ -348,7 +352,7 @@ func (e *encoder) encodeMapEntries(json []byte, v reflect.Value) ([]byte, error)
348352 }
349353 encodedKeyString = string (encodedKeyBytes )
350354 }
351- encodedKey := []byte (sjsonReplacer . Replace ( encodedKeyString ) )
355+ encodedKey := []byte (encodedKeyString )
352356 pairs = append (pairs , mapPair {key : encodedKey , value : iter .Value ()})
353357 }
354358
@@ -366,7 +370,7 @@ func (e *encoder) encodeMapEntries(json []byte, v reflect.Value) ([]byte, error)
366370 if len (encodedValue ) == 0 {
367371 continue
368372 }
369- json , err = sjson .SetRawBytes (json , string (p .key ), encodedValue )
373+ json , err = sjson .SetRawBytes (json , EscapeSJSONKey ( string (p .key ) ), encodedValue )
370374 if err != nil {
371375 return nil , err
372376 }
@@ -386,7 +390,3 @@ func (e *encoder) newMapEncoder(_ reflect.Type) encoderFunc {
386390 return json , nil
387391 }
388392}
389-
390- // If we want to set a literal key value into JSON using sjson, we need to make sure it doesn't have
391- // special characters that sjson interprets as a path.
392- var sjsonReplacer * strings.Replacer = strings .NewReplacer ("." , "\\ ." , ":" , "\\ :" , "*" , "\\ *" )
0 commit comments