@@ -16,6 +16,10 @@ import (
16
16
17
17
var encoders sync.Map // map[encoderEntry]encoderFunc
18
18
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
+
19
23
func Marshal (value any ) ([]byte , error ) {
20
24
e := & encoder {dateFormat : time .RFC3339 }
21
25
return e .marshal (value )
@@ -270,7 +274,7 @@ func (e *encoder) newStructTypeEncoder(t reflect.Type) encoderFunc {
270
274
if encoded == nil {
271
275
continue
272
276
}
273
- json , err = sjson .SetRawBytes (json , ef .tag .name , encoded )
277
+ json , err = sjson .SetRawBytes (json , EscapeSJSONKey ( ef .tag .name ) , encoded )
274
278
if err != nil {
275
279
return nil , err
276
280
}
@@ -348,7 +352,7 @@ func (e *encoder) encodeMapEntries(json []byte, v reflect.Value) ([]byte, error)
348
352
}
349
353
encodedKeyString = string (encodedKeyBytes )
350
354
}
351
- encodedKey := []byte (sjsonReplacer . Replace ( encodedKeyString ) )
355
+ encodedKey := []byte (encodedKeyString )
352
356
pairs = append (pairs , mapPair {key : encodedKey , value : iter .Value ()})
353
357
}
354
358
@@ -366,7 +370,7 @@ func (e *encoder) encodeMapEntries(json []byte, v reflect.Value) ([]byte, error)
366
370
if len (encodedValue ) == 0 {
367
371
continue
368
372
}
369
- json , err = sjson .SetRawBytes (json , string (p .key ), encodedValue )
373
+ json , err = sjson .SetRawBytes (json , EscapeSJSONKey ( string (p .key ) ), encodedValue )
370
374
if err != nil {
371
375
return nil , err
372
376
}
@@ -386,7 +390,3 @@ func (e *encoder) newMapEncoder(_ reflect.Type) encoderFunc {
386
390
return json , nil
387
391
}
388
392
}
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