flightcontrolhq / superjson

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
https://www.flightcontrol.dev?ref=superjson
MIT License
4.01k stars 87 forks source link

Is there a way to get just the string value inside `json` when doing stringify? #254

Open nooblyf opened 1 year ago

nooblyf commented 1 year ago

when i stringify anything i get json and meta (or sometimes just json) like this

stringify({
  flasjhdfojha: 45234524,
  fadsfasd: { fasfd: { dfasdfasdf: { fasdfasd: 341234123, date: new Date() } } },
})
// {"json":{"flasjhdfojha":45234524,"fadsfasd":{"fasfd":{"dfasdfasdf":{"fasdfasd":341234123,"date":"2023-08-05T19:39:45.674Z"}}}},"meta":{"values":{"fadsfasd.fasfd.dfasdfasdf.date":["Date"]}}}

stringify("helooooo")
// {"json":"helooooo"}

is there a way to get just the value inside json as a string? something like

// string
// {"flasjhdfojha":45234524,"fadsfasd":{"fasfd":{"dfasdfasdf":{"fasdfasd":341234123,"date":"2023-08-05T19:39:45.674Z"}}}}

// string
// helooooo

what i'm currently doing is using regex to remove json (key) and meta completely (if it exists)

stringify(data).replace(/^(({\"json\":?)(\"?))|(,"meta":.*)|((\"?)(}?$))/gi, '');
Skn0tt commented 1 year ago

Hi @nooblyf! You could use SuperJSON.serialize, grab the json key and stringify that using JSON.stringify. That means all type information will be lost, though, losing the main benefit of SuperJSON. Depending on what you're looking for, JSON's replacer option might be a better fit.

nooblyf commented 1 year ago

I wanted this for logging purposes only, i guess JSON.stringify is the way to go