Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Created August 28, 2020 15:11
Show Gist options
  • Save tomhodgins/1ed24e50aff165d82df2fb2c7aa729f2 to your computer and use it in GitHub Desktop.
Save tomhodgins/1ed24e50aff165d82df2fb2c7aa729f2 to your computer and use it in GitHub Desktop.
You can define how an object stringifies with String() and toString(), and how it represents itself when converted to JSON
({
value: 'hello world',
toString() { return `stringified that's: ${this.value}` }
}).toString()
// "stringified that's: hello world"
JSON.stringify({
value: 'hello world',
toJSON() { return [{JSONified_thats: this.value}] }
})
// "[{"JSONified_thats":"hello world"}]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment