Skip to content

Instantly share code, notes, and snippets.

@djD-REK
Last active August 26, 2019 22:32
Show Gist options
  • Save djD-REK/1b76ad6c988b58f5c8d455c5b04b0efc to your computer and use it in GitHub Desktop.
Save djD-REK/1b76ad6c988b58f5c8d455c5b04b0efc to your computer and use it in GitHub Desktop.
// Let's take this JavaScript object and turn it into JSON
// Stringify should work -- it turns objects to JSON strings
// Parse should fail -- it turns JSON strings to objects
const myJavaScriptObject = {
dog: "πŸ•",
cat: "🐈",
koala: "🐨",
count: 3
};
// Before ES2019 -- Need to reference caught error
try {
console.log(JSON.parse(myJavaScriptObject));
} catch (error) {
console.log(error + "");
}
// result: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
// Works in ECMAScript2019 -- Leave out error
try {
console.log(JSON.parse(myJavaScriptObject));
} catch (error) {
console.log("Whoops! That did not seem to be a JSON String... ");
}
// result: Whoops! That did not seem to be a JSON String...
// ES2019: No error, no problem -- we don't even really have to "catch it" as a parameter
try {
console.log(JSON.stringify(myJavaScriptObject));
} catch {
console.log("Whoops! That did not seem to be a JSON String... ");
}
// result: {"dog":"πŸ•","cat":"🐈","koala":"🐨","count":3}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment