Skip to content

Commit 8dd259f

Browse files
authored
Merge pull request #3031 from dolthub/elianddb/fix-7998-json-escape-double-quotes
Key write now uses same recursive call to writeMarshalledValue() as value under json_encode.go Fixes: dolthub/dolt#7998
2 parents 48f6247 + 5c70af8 commit 8dd259f

File tree

3 files changed

+52
-4
lines changed

3 files changed

+52
-4
lines changed

enginetest/queries/json_scripts.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,44 @@ var JsonScripts = []ScriptTest{
187187
},
188188
},
189189
},
190+
{
191+
Name: "json_object preserves escaped characters in key and values",
192+
Assertions: []ScriptTestAssertion{
193+
{
194+
Query: `select cast(JSON_OBJECT('key"with"quotes\n','3"\\') as char);`,
195+
Expected: []sql.Row{
196+
{`{"key\"with\"quotes\n": "3\"\\"}`},
197+
},
198+
},
199+
},
200+
},
201+
{
202+
Name: "json conversion works with escaped characters",
203+
Assertions: []ScriptTestAssertion{
204+
{
205+
Query: `SELECT CAST(CAST(JSON_OBJECT('key"with"quotes', 1) as CHAR) as JSON);`,
206+
Expected: []sql.Row{
207+
{`{"key\"with\"quotes": 1}`},
208+
},
209+
},
210+
},
211+
},
212+
{
213+
Name: "json_object with escaped k:v pairs from table",
214+
SetUpScript: []string{
215+
`CREATE TABLE IF NOT EXISTS textt_7998 (t text);`,
216+
`INSERT INTO textt_7998 VALUES ('first row\n\\'), ('second row"');`,
217+
},
218+
Assertions: []ScriptTestAssertion{
219+
{
220+
Query: `SELECT JSON_OBJECT(t, t) FROM textt_7998;`,
221+
Expected: []sql.Row{
222+
{types.MustJSON(`{"first row\n\\": "first row\n\\"}`)},
223+
{types.MustJSON(`{"second row\"": "second row\""}`)},
224+
},
225+
},
226+
},
227+
},
190228
{
191229
Name: "json_value preserves types",
192230
Assertions: []ScriptTestAssertion{

sql/types/json_encode.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -210,10 +210,12 @@ func writeMarshalledValue(writer io.Writer, val interface{}) error {
210210

211211
writer.Write([]byte{'{'})
212212
for i, k := range keys {
213-
writer.Write([]byte{'"'})
214-
writer.Write([]byte(k))
215-
writer.Write([]byte(`": `))
216-
err := writeMarshalledValue(writer, val[k])
213+
err := writeMarshalledValue(writer, k)
214+
if err != nil {
215+
return err
216+
}
217+
writer.Write([]byte(`: `))
218+
err = writeMarshalledValue(writer, val[k])
217219
if err != nil {
218220
return err
219221
}

sql/types/json_encode_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,14 @@ newlines
106106
val: decimal.New(123, -2),
107107
expected: "1.23",
108108
},
109+
{
110+
name: "formatted key strings",
111+
val: map[string]interface{}{
112+
"baz\n\\n": "qux",
113+
"foo\"": "bar\t",
114+
},
115+
expected: `{"foo\"": "bar\t", "baz\n\\n": "qux"}`,
116+
},
109117
}
110118

111119
for _, test := range tests {

0 commit comments

Comments
 (0)