Everything You Need To Know About JSON.stringify and JSON.parse
JSON is probably one of the most underrated programming language in existence. Not only is it so widespread, it’s lightweight and no-nonsense demeanor makes JSON feel almost native to whichever language it pairs up with.
Yes. That’s right. JSON is it’s own language, despite becoming somewhat synonymous with JavaScript.
Over the years, other languages have picked up support and steered away from the other potential option like XML and YAML. It didn’t take long for JSON to officially take over everything and act as the bridge between backends and frontends, frameworks and libraries, transmitting and translating data back and forth between the different places and spaces.
So where does the drama with toString()
come in?
Well, let’s start by pretending that we need to turn an object into a string.
Making objects into strings
There are times where you just want to return a string instead of a complex object. For example, you want to send it over a network or output it for logging purposes.
Rather than getting that annoying [object Object]
output via console log, you just want it to print as a string so you can quickly debug and scan the returned data.
To do this, in theory, use the toString()
method. But the syntax for this can end up being cumbersome in the long run.
How and why?
The thing with toString()
and objects is that it returns the literal description rather than the contents inside. So rather than getting something like {firstName:"Jane", lastName:"Doe"}
you get the lovely [object Object]
This, naturally, isn’t that helpful, especially when you want to do something directly with that string.
For toString()
to work properly in turning objects into strings, you need to break it up and manually abstract out each key-pair values.
For example:
test = {website:"dottedsquirrel.com",
toString(){
return `{website:"${this.website}"}`;
}}
console.log(test.toString());
Yes, toString()
does work elegantly with numbers, but not so much when it comes to objects.