Skip to content

Commit beec790

Browse files
authored
fix encoding with map key contains colon character (#604)
1 parent e2e4400 commit beec790

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

encode.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,17 @@ func (e *Encoder) isNeedQuoted(v string) bool {
538538
if e.isFlowStyle && strings.ContainsAny(v, `]},'"`) {
539539
return true
540540
}
541+
if e.isFlowStyle {
542+
for i := 0; i < len(v); i++ {
543+
if v[i] != ':' {
544+
continue
545+
}
546+
if i+1 < len(v) && v[i+1] == '/' {
547+
continue
548+
}
549+
return true
550+
}
551+
}
541552
if token.IsNeedQuoted(v) {
542553
return true
543554
}

encode_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"math"
99
"reflect"
1010
"strconv"
11+
"strings"
1112
"testing"
1213
"time"
1314

@@ -1654,3 +1655,23 @@ b:
16541655
t.Fatalf("failed to encode. expected %s but got %s", expected, got)
16551656
}
16561657
}
1658+
1659+
type Issue174 struct {
1660+
K string
1661+
V []int
1662+
}
1663+
1664+
func (v Issue174) MarshalYAML() ([]byte, error) {
1665+
return yaml.MarshalWithOptions(map[string][]int{v.K: v.V}, yaml.Flow(true))
1666+
}
1667+
1668+
func TestIssue174(t *testing.T) {
1669+
b, err := yaml.Marshal(Issue174{"00:00:00-23:59:59", []int{1, 2, 3}})
1670+
if err != nil {
1671+
t.Fatal(err)
1672+
}
1673+
got := strings.TrimSuffix(string(b), "\n")
1674+
if got != `{"00:00:00-23:59:59": [1, 2, 3]}` {
1675+
t.Fatalf("failed to encode: %q", got)
1676+
}
1677+
}

0 commit comments

Comments
 (0)