-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathjson.ts
37 lines (35 loc) · 896 Bytes
/
json.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Wraps parsing of JSON, so that an error is logged, but no exception is thrown
*/
export function safeParseJson<T = unknown> (value?: string|false|null) : T|null
{
if (value)
{
try
{
const content = value.trim();
return (content !== "")
? JSON.parse(content) as T
: null;
}
catch (e)
{
console.error(`Could not parse JSON content: ${e.message}`, e);
}
}
return null;
}
/**
* Parses JSON from the given element's content.
*/
export function parseElementAsJson<T = unknown> (element: HTMLElement|null) : T|null
{
return null !== element
? safeParseJson<T>(
(element.textContent || "")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/&/g, "&")
)
: null;
}