Created
January 21, 2020 15:07
-
-
Save coderwurst/81f7b4a0c44c096cb0cc7b8a6a0b9d36 to your computer and use it in GitHub Desktop.
JSON Stringify examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
JS Result | |
EDIT ON | |
const firstItem = { | |
title: 'Transformers', | |
year: 2007 | |
}; | |
console.log(JSON.stringify(firstItem)); | |
const secondItem = { | |
title: 'Transformers', | |
year: 2007, | |
starring: new Map([[0, 'Shia LaBeouf'],[1, 'Megan Fox']]) | |
}; | |
console.log(JSON.stringify(secondItem)); | |
console.log(JSON.stringify(secondItem, ['title'])); | |
console.log(JSON.stringify(secondItem, (key, value) => { | |
if (value instanceof Map) { | |
return [...value.values()]; | |
} | |
return value; | |
})); | |
console.log(JSON.stringify(secondItem, (key, value) => { | |
if (typeof value === 'string') { | |
return undefined; | |
} | |
return value; | |
})); | |
console.log(JSON.stringify(secondItem, null, 2)); | |
console.log(JSON.stringify(secondItem, null, '🦄')); | |
const thirdItem = { | |
title: 'Transformers', | |
year: 2007, | |
starring: new Map([[0, 'Shia LaBeouf'],[1, 'Megan Fox']]), | |
toJSON() { | |
return { | |
name: `${this.title} (${this.year})`, | |
actors: [...this.starring.values()] | |
}; | |
} | |
}; | |
console.log(JSON.stringify(thirdItem)); | |
Resources |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment