Skip to content

Instantly share code, notes, and snippets.

@erming
Last active July 16, 2024 14:59
Show Gist options
  • Save erming/ea6c5a23bc051fa7398d481274ec5f72 to your computer and use it in GitHub Desktop.
Save erming/ea6c5a23bc051fa7398d481274ec5f72 to your computer and use it in GitHub Desktop.
function tryParseJson(string) {
try {
const output = JSON.parse(string);
if (output && typeof output === "object") {
return output;
}
} catch {}
return null;
}
let a = tryParseJson("a");
let b = tryParseJson("1");
let c = tryParseJson("true");
let d = tryParseJson("false");
let e = tryParseJson("null");
let f = tryParseJson("");
let g = tryParseJson("{}");
let h = tryParseJson("[]");
let i = tryParseJson("[1,2,3]");
let j = tryParseJson("[1,{},3]");
let k = tryParseJson("{\"a\":1}");
let l = tryParseJson();
let m = tryParseJson(undefined);
let n = tryParseJson(null);
console.log({
a, // null
b, // null
c, // null
d, // null
e, // null
f, // null
g, // {}
h, // []
i, // [1, 2, 3]
j, // [1, {...}, 3]
k, // {a: 1}
l, // null
m, // null
n, // null
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment