Skip to content

Encode json.Number as a number, not a quoted string - #445

Open
vsaraikin wants to merge 1 commit into
mailru:masterfrom
vsaraikin:fix/json-number-encoding
Open

Encode json.Number as a number, not a quoted string#445
vsaraikin wants to merge 1 commit into
mailru:masterfrom
vsaraikin:fix/json-number-encoding

Conversation

@vsaraikin

Copy link
Copy Markdown

Fixes #220

json.Number fields are generated as out.String(string(v)), so they come out quoted:

{"int":"123","float":"10.00"}

encoding/json writes them as raw numbers. Decoding was already brought in line in #145, #163 and #172, encoding was left behind.

This adds a customEncoders map in gen, mirroring the existing customDecoders, so json.Number routes to a new Writer.JsonNumber instead of the string encoder. The writer follows encoding/json: an empty Number is written as 0 and an invalid literal sets w.Error rather than emitting broken JSON. isValidNumber is the grammar check copied from encoding/json so the accepted set is identical.

tests/json_number.go covers the round trip through the generated code, plus jwriter tests for the empty and invalid cases. The Makefile picks up the new fixture and adds ./jwriter to the test target, which was not being run.

Reverting only the gen change makes the new case fail with the quoted output above

The decoder has a custom json.Number path (in.JsonNumber()), but the encoder
treated json.Number as its underlying string kind and emitted it quoted, so
round-tripping changed the JSON type from number to string. Add the encoder
counterpart: customEncoders routes json.Number to a new jwriter.JsonNumber,
which writes the literal raw, encodes the empty value as 0 and errors on
invalid literals, matching encoding/json. Fixes mailru#220.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

json.Number marshaled as text instead of number

1 participant