Fix mod flatten including non-existent arrays

This commit is contained in:
tidwall 2021-03-25 08:28:15 -07:00
parent b61527bf1a
commit c75c954102
2 changed files with 23 additions and 12 deletions

View File

@ -2176,11 +2176,6 @@ func parseAny(json string, i int, hit bool) (int, Result, bool) {
return i, res, false return i, res, false
} }
var ( // used for testing
testWatchForFallback bool
testLastWasFallback bool
)
// GetMany searches json for the multiple paths. // GetMany searches json for the multiple paths.
// The return value is a Result array where the number of items // The return value is a Result array where the number of items
// will be equal to the number of input paths. // will be equal to the number of input paths.
@ -2745,19 +2740,24 @@ func modFlatten(json, arg string) string {
out = append(out, '[') out = append(out, '[')
var idx int var idx int
res.ForEach(func(_, value Result) bool { res.ForEach(func(_, value Result) bool {
if idx > 0 { var raw string
out = append(out, ',')
}
if value.IsArray() { if value.IsArray() {
if deep { if deep {
out = append(out, unwrap(modFlatten(value.Raw, arg))...) raw = unwrap(modFlatten(value.Raw, arg))
} else { } else {
out = append(out, unwrap(value.Raw)...) raw = unwrap(value.Raw)
} }
} else { } else {
out = append(out, value.Raw...) raw = value.Raw
}
raw = strings.TrimSpace(raw)
if len(raw) > 0 {
if idx > 0 {
out = append(out, ',')
}
out = append(out, raw...)
idx++
} }
idx++
return true return true
}) })
out = append(out, ']') out = append(out, ']')

View File

@ -787,6 +787,12 @@ var manyJSON = ` {
func combine(results []Result) string { func combine(results []Result) string {
return fmt.Sprintf("%v", results) return fmt.Sprintf("%v", results)
} }
var ( // used for testing
testWatchForFallback bool
testLastWasFallback bool
)
func TestManyBasic(t *testing.T) { func TestManyBasic(t *testing.T) {
testWatchForFallback = true testWatchForFallback = true
defer func() { defer func() {
@ -2222,3 +2228,8 @@ func TestSubpathsWithMultipaths(t *testing.T) {
assert(t, Get(json, `#.@ugly`).Raw == `[{"a":1},{"a":2,"values":["a","b","c","d","e"]},true,["a","b","c","d","e"],4]`) assert(t, Get(json, `#.@ugly`).Raw == `[{"a":1},{"a":2,"values":["a","b","c","d","e"]},true,["a","b","c","d","e"],4]`)
assert(t, Get(json, `#.[0,3]`).Raw == `[[],[],[],["a","d"],[]]`) assert(t, Get(json, `#.[0,3]`).Raw == `[[],[],[],["a","d"],[]]`)
} }
func TestFlattenRemoveNonExist(t *testing.T) {
raw := Get("[[1],[2,[[],[3]],[4,[5],[],[[[6]]]]]]", `@flatten:{"deep":true}`).Raw
assert(t, raw == "[1,2,3,4,5,6]")
}