@@ -18,6 +18,10 @@ import (
18
18
19
19
var encoders sync.Map // map[encoderEntry]encoderFunc
20
20
21
+ // If we want to set a literal key value into JSON using sjson, we need to make sure it doesn't have
22
+ // special characters that sjson interprets as a path.
23
+ var EscapeSJSONKey = strings .NewReplacer ("\\ " , "\\ \\ " , "|" , "\\ |" , "#" , "\\ #" , "@" , "\\ @" , "*" , "\\ *" , "." , "\\ ." , ":" , "\\ :" , "?" , "\\ ?" ).Replace
24
+
21
25
func Marshal (value interface {}) ([]byte , error ) {
22
26
e := & encoder {dateFormat : time .RFC3339 }
23
27
return e .marshal (value )
@@ -276,7 +280,7 @@ func (e *encoder) newStructTypeEncoder(t reflect.Type) encoderFunc {
276
280
if encoded == nil {
277
281
continue
278
282
}
279
- json , err = sjson .SetRawBytes (json , ef .tag .name , encoded )
283
+ json , err = sjson .SetRawBytes (json , EscapeSJSONKey ( ef .tag .name ) , encoded )
280
284
if err != nil {
281
285
return nil , err
282
286
}
@@ -354,7 +358,7 @@ func (e *encoder) encodeMapEntries(json []byte, v reflect.Value) ([]byte, error)
354
358
}
355
359
encodedKeyString = string (encodedKeyBytes )
356
360
}
357
- encodedKey := []byte (sjsonReplacer . Replace ( encodedKeyString ) )
361
+ encodedKey := []byte (encodedKeyString )
358
362
pairs = append (pairs , mapPair {key : encodedKey , value : iter .Value ()})
359
363
}
360
364
@@ -372,7 +376,7 @@ func (e *encoder) encodeMapEntries(json []byte, v reflect.Value) ([]byte, error)
372
376
if len (encodedValue ) == 0 {
373
377
continue
374
378
}
375
- json , err = sjson .SetRawBytes (json , string (p .key ), encodedValue )
379
+ json , err = sjson .SetRawBytes (json , EscapeSJSONKey ( string (p .key ) ), encodedValue )
376
380
if err != nil {
377
381
return nil , err
378
382
}
@@ -392,7 +396,3 @@ func (e *encoder) newMapEncoder(t reflect.Type) encoderFunc {
392
396
return json , nil
393
397
}
394
398
}
395
-
396
- // If we want to set a literal key value into JSON using sjson, we need to make sure it doesn't have
397
- // special characters that sjson interprets as a path.
398
- var sjsonReplacer * strings.Replacer = strings .NewReplacer ("." , "\\ ." , ":" , "\\ :" , "*" , "\\ *" )
0 commit comments