as-json icon indicating copy to clipboard operation
as-json copied to clipboard

JSON.stringify encodes JSON.Raw as string

Open anisus opened this issue 1 year ago • 2 comments

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}}`

anisus avatar Nov 27 '24 15:11 anisus

I ran into this as well. Map<string, JSON.Raw> doesn't work either (for stringify or parse).

mattjohnsonpint avatar Dec 06 '24 22:12 mattjohnsonpint

I'll take a look into it--its likely going to be a pain to implement, but you should be able to expect it with the next release

JairusSW avatar Dec 06 '24 23:12 JairusSW

Fixed. JSON.Raw is now it's own class, so it works anywhere. Check the README for an example: https://github.com/JairusSW/json-as?tab=readme-ov-file#%EF%B8%8F-using-raw-json-strings

JairusSW avatar Mar 06 '25 21:03 JairusSW