Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- The JSON writer no longer escapes `<`, `>` and `&` as `\u003c`, `\u003e` and `\u0026`. That escaping is only needed when embedding JSON in HTML, so e.g. `dasel -i toml -o json` now emits `"setuptools>=77.0.3"` rather than `"setuptools\u003e=77.0.3"` ([#552](https://github.com/TomWright/dasel/issues/552)).
- The TOML writer no longer relies on go-toml encoding a bare value as a document root, which go-toml v2.4 rejects. Selecting a scalar or list and writing it as TOML (e.g. `dasel -i json -o toml 'hello'`) works again.
- Writing a list of tables as the top level value now emits a valid inline array of tables (e.g. `[{a = 1}, {a = 2}]`) instead of table headers with an empty key.

Expand Down
29 changes: 29 additions & 0 deletions parsing/json/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,35 @@ func TestJsonCompact(t *testing.T) {
}
}

func TestJsonDoesNotEscapeHTMLCharacters(t *testing.T) {
doc := []byte(`{
"string": "setuptools>=77.0.3 & <b>"
}
`)
reader, err := json.JSON.NewReader(parsing.DefaultReaderOptions())
if err != nil {
t.Fatal(err)
}
writer, err := json.JSON.NewWriter(parsing.DefaultWriterOptions())
if err != nil {
t.Fatal(err)
}

value, err := reader.Read(doc)
if err != nil {
t.Fatal(err)
}

newDoc, err := writer.Write(value)
if err != nil {
t.Fatal(err)
}

if string(doc) != string(newDoc) {
t.Fatalf("expected %s, got %s...\n%s", string(doc), string(newDoc), cmp.Diff(string(doc), string(newDoc)))
}
}

func TestNDJSON(t *testing.T) {
newReader := func(t *testing.T) parsing.Reader {
t.Helper()
Expand Down
12 changes: 9 additions & 3 deletions parsing/json/json_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,17 @@ func (j *jsonWriter) Write(value *model.Value) ([]byte, error) {
}

encoderFn := func(v any) error {
res, err := json.Marshal(v)
if err != nil {
// json.Marshal escapes <, > and & as \u003c, \u003e and \u0026.
// That is only required when embedding JSON in HTML, so use an
// encoder with HTML escaping disabled to keep the output readable.
valBuf := new(bytes.Buffer)
enc := json.NewEncoder(valBuf)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return err
}
_, err = buf.Write(res)
// Encode appends a trailing newline that we do not want here.
_, err := buf.Write(bytes.TrimSuffix(valBuf.Bytes(), []byte("\n")))
return err
}

Expand Down
Loading