JavaScript Object Notation
JSON is a widely used format for exchanging data that is used in JavaScript programs.
When a program stores structured data or requests information from a web server, the response will often be formatted in JSON.
The JSON.parse
function allows you to decode a JSON-formatted string into JavaScript values like string
, number
, and boolean
,
while the JSON.stringify
function converts a JavaScript value into a JSON-formatted string.
Since TypeScript cannot infer the actual data types that will be generated by parsing a JSON string, the result of JSON.parse
has the type any
.
If you are sure about the data type contained in a JSON string, you can use the as
keyword to apply a type to the result.
If your assumption is incorrect, your program will encounter the same runtime error that the same JavaScript program would encounter.
As you encounter other data types of TypeScript, this cursory introduction to JSON.parse
and JSON.stringify
will be expanded to include details
on how those data types should be parsed and stringified.