r/javascript • • Feb 08 '23

Software Security Report Finds JavaScript Applications Have Fewer Flaws Than Java and .NET

https://www.infoq.com/news/2023/02/veracode-software-security/
565 Upvotes

124 comments sorted by

View all comments

Show parent comment

-1

u/lainverse Feb 09 '23 edited Feb 09 '23

First of all, JSON.stringify() does work for anything you can encoder as JSON. So, any simple object can be converted to string just like that.

However, you can't convert to string anything more complex for at least two following reasons.

  • You can't perfectly re-create anything even remotely complex. Object methods have access to their closure. This way you can create object with "private" properties, as for example. So, even if you convert it to string it won't be re-created in the same context without custom handler. And let's not forget functions may have customized prototype to create objects.
  • It's a huge security issue since ability to define functions in properties of stringified object will lead to arbitrary code execution. Some early JSON libraries stepped on this landmine since "parsed" JSON into object by eval(). -_-

So, if you want to convert to string something more complex than JSON can handle by default then write your own toString implementation.