Last active
August 26, 2019 22:32
-
-
Save djD-REK/1b76ad6c988b58f5c8d455c5b04b0efc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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