@@ -18,6 +18,10 @@ import (
1818
1919var encoders sync.Map // map[encoderEntry]encoderFunc
2020
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+
2125func Marshal (value interface {}) ([]byte , error ) {
2226 e := & encoder {dateFormat : time .RFC3339 }
2327 return e .marshal (value )
@@ -276,7 +280,7 @@ func (e *encoder) newStructTypeEncoder(t reflect.Type) encoderFunc {
276280 if encoded == nil {
277281 continue
278282 }
279- json , err = sjson .SetRawBytes (json , ef .tag .name , encoded )
283+ json , err = sjson .SetRawBytes (json , EscapeSJSONKey ( ef .tag .name ) , encoded )
280284 if err != nil {
281285 return nil , err
282286 }
@@ -354,7 +358,7 @@ func (e *encoder) encodeMapEntries(json []byte, v reflect.Value) ([]byte, error)
354358 }
355359 encodedKeyString = string (encodedKeyBytes )
356360 }
357- encodedKey := []byte (sjsonReplacer . Replace ( encodedKeyString ) )
361+ encodedKey := []byte (encodedKeyString )
358362 pairs = append (pairs , mapPair {key : encodedKey , value : iter .Value ()})
359363 }
360364
@@ -372,7 +376,7 @@ func (e *encoder) encodeMapEntries(json []byte, v reflect.Value) ([]byte, error)
372376 if len (encodedValue ) == 0 {
373377 continue
374378 }
375- json , err = sjson .SetRawBytes (json , string (p .key ), encodedValue )
379+ json , err = sjson .SetRawBytes (json , EscapeSJSONKey ( string (p .key ) ), encodedValue )
376380 if err != nil {
377381 return nil , err
378382 }
@@ -392,7 +396,3 @@ func (e *encoder) newMapEncoder(t reflect.Type) encoderFunc {
392396 return json , nil
393397 }
394398}
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