Skip to main content

The Language APIs Speak

APIs exchange data as JSON — text like {"id": 1, "name": "Ana"}. TypeScript needs no library for it: JSON.stringify turns a value into JSON text and JSON.parse turns JSON text back into a value. Both come from JavaScript itself.

An interface describes the shape you expect on either side. There is no special syntax for renaming a field: the key in the JSON is the property name exactly as you wrote it. When a key must have a different name, you rename it by hand — when you build the object, or right after you parse it.


From Object to JSON

JSON.stringify(value) produces compact JSON for machines; JSON.stringify(value, null, 2) indents it by two spaces for humans and logs.

An optional property (written email?: string) that was never set is simply left out of the JSON — no empty key appears.

Compact and pretty JSON

Ana has no email, so the email key is missing from her JSON entirely. Ben's full record prints indented.

Prompt
Write a TypeScript program with a UserRecord interface whose email property is optional. Stringify a user without an email compactly, and a full user with two-space indentation, printing both JSON results.
Output: TypeScript file and captured output

From JSON to Object

JSON.parse returns the parsed value, and as UserRecord tells the type checker what you expect to find. Bad JSON does not hand back an error value — it throws, so wrap the call in try/catch.

One thing to know: unknown keys are not dropped. JSON.parse keeps every key the text contains; the interface only describes what you promise to use. When you want a clean object, copy out the fields you need.

Parsing, and the extra key

The JSON carries an extra key that the interface never mentions. Nothing fails — the key is really there at run time, and copying the two fields you want gives the clean { id: 7, name: 'Cleo' }. Broken JSON throws, and the catch prints the message.

Prompt
Write a TypeScript program that parses a JSON string carrying an extra unknown key into a UserRecord, prints the parsed object, then prints a clean copy holding only id and name. Finally try to parse broken JSON inside try/catch and print the error message.
Output: TypeScript file and captured output

Nested Data

Real API payloads nest: an order carries its user and a list of items. Objects inside objects and arrays map to JSON objects and arrays automatically — no special handling needed.

An order with a user inside

The nested user object becomes a nested JSON object, the items array becomes a JSON array — the shape of the data is the shape of the JSON.

Prompt
Write a TypeScript program with an OrderRecord interface holding an id, an array of item names and a nested UserRecord. Stringify one order with two-space indentation and print it to show nested objects and arrays.
Output: TypeScript file and captured output