Skip to content
This repository was archived by the owner on Mar 31, 2023. It is now read-only.

Fix JSONFormat to output valid JSON strings #33

Merged
merged 1 commit into from
Jan 23, 2023

Conversation

itchyny
Copy link
Contributor

@itchyny itchyny commented Apr 6, 2022

This PR fixes JSONFormat to output valid JSON strings regardless of the fields data, resolves #31.

@itchyny itchyny force-pushed the fix-json-string branch 2 times, most recently from 77a0232 to 416cf74 Compare April 12, 2022 13:43
@itchyny itchyny force-pushed the fix-json-string branch 2 times, most recently from a662d91 to 46a9527 Compare January 20, 2023 09:28
@@ -316,3 +307,53 @@ func appendFloat(buf []byte, v float64, bitSize int) []byte {
return strconv.AppendFloat(buf, v, 'f', -1, bitSize)
}
}

// Ref: encodeState#string in encoding/json.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This implementation might look kind of a horrible idea causing code duplicates, but I don't think there's a better way to solve the original issue with no allocation overhead. I hope there is json.AppendMarshal([]byte, v any) ([]byte, error) in encoding/json package.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another solution is to create a writer wrapping a bytes.Buffer to use json.Encoder.Encode, just like I'm proposing in different package (https://github.com/hokaccha/go-prettyjson/pull/21/files#diff-2fc4cc94d53b67bb93f26e56ef7ee4b2344b0b20970b9b971cbf418f4fc31818R233-R244), but this is actually slower than directly appending to []byte for maximum performance like this log package.

@itchyny itchyny marked this pull request as ready for review January 20, 2023 15:25
@morimoto-cybozu morimoto-cybozu merged commit 8baa864 into cybozu-go:main Jan 23, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

JSONFormat outputs non-JSON on some non-printable characters
2 participants