as-json
as-json copied to clipboard
JSON.stringify encodes JSON.Raw as string
Issue
When encoding a value of type JSON.Raw
using JSON.stringify
, the value is encoded as if it was a string:
const raw: JSON.Raw = `{"foo":42}`;
const json = JSON.stringify(raw);
// Expected json to be: `{"foo":42}`
// but got: `"{\"foo\":42}"`
Notes
I ran into the problem when making a generic function that took any type T
that could be encoded to json:
function send<T>(value: T): void {
const dta = JSON.stringify(value);
/* ... */
}
The issue does NOT occur if a class has a property of type JSON.Raw
:
@json
class myClass {
data: JSON.Raw = "null";
}
const cl = new myClass();
cl.data = `{"foo":42}`;
const json = JSON.stringify(cl);
// Results in expected json: `{"data":{"foo":42}}`