Typescript types have no runtime component. You either need to write something or convert your typescript types to something else to replicate that. And for the latter, I would recommend taking care with just translating files wholecloth (like typescript-to-zod) because TS was not designed to make efficient use of runtime validators. The correct way to handle incoming JSON is to use a dedicated runtime validator. I don't traditionally love this, but most TS developers agree that it's ok to break DRY a bit to implement this. You can, however, use a lib like zod and apply a runtime assertion that zod's type is producing an identical signature to the source type. This link shows a way to do that: https://github.com/colinhacks/zod/issues/372#issuecomment-810895037 Ultimately, what do you want to happen if the runtime type signature changes? If you want to fail, the above link explains how. If you want to "warn but try anyway", I'm sure that code will help you figure the best way to do that. So the pattern I'd suggest looks like: Build zod versions (possibly MORE strict) of the interface When handling input: Validate the input is correct Validate that zod is still a correct representation of the upstream types Return valid data, already coerced by zod into final-form types. Answer from novagenesis on reddit.com
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › parse
JSON.parse() - JavaScript | MDN
JSON.parse() parses a JSON string according to the JSON grammar, then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the "__proto__" key — see Object ...
🌐
Manuals+
manuals.plus › viewer › tools › typescript › json-parse
TypeScript JSON.parse() Online
1 month ago - Free online manuals and user guides for appliances, electronics, vehicles, and tools. Search by brand or model and download PDFs to support repair.
🌐
Reddit
reddit.com › r/typescript › how to parse json into typescript types?
r/typescript on Reddit: How to parse json into typescript types?
January 16, 2023 -
export type HoppEnvPair = { key: string; value: string };

export type HoppEnvs = {
  global: HoppEnvPair[];
  selected: HoppEnvPair[];
};

I have types defined in an upstream package. Is there a library to parse json to a type safe object like `parse(json, TopLevelType)` that can point out validation errors too? I looked at TypedJson, Class Transformer, Zod (nice tiny package) etc but they require me to rewrite those upstream package types as classes or schemas.

I have half a mind to write a schema that parses json to a schema specific object, and then manually convert to upstream types. This seems verbose but it could be typesafe and more straightforward than parsing manually.

🌐
TutorialKart
tutorialkart.com › typescript › typescript-parse-json-string
TypeScript - Parse JSON String
December 1, 2020 - To parse a JSON string in TypeScript, you can use JSON.parse().
🌐
Choly
choly.ca › post › typescript-json
TypeScript: Working with JSON · Choly's Blog
March 19, 2016 - class User { private created: Date; constructor( private name: string, private age: string ) { this.created = new Date(); } getName(): string { return this.name; } // toJSON is automatically used by JSON.stringify toJSON(): UserJSON { // copy all fields from `this` to an empty object and return in return Object.assign({}, this, { // convert fields that need converting created: this.created.toString() }); } // fromJSON is used to convert an serialized version // of the User to an instance of the class static fromJSON(json: UserJSON|string): User { if (typeof json === 'string') { // if it's a st
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › build-a-custom-pdf-text-extractor-with-nodejs-and-typescript
How to Build a Custom PDF Text Extractor with Node.js and TypeScript
1 month ago - The function converts the uploaded PDF file to a Uint8Array buffer format, which is required by the getPDFMetadata() utility function you created earlier. This conversion ensures the PDF data is in the proper format for the PDF parsing library to process. After successfully extracting metadata, the route logs the results and returns them in a structured JSON response.
🌐
Kubb
kubb.dev
Kubb - TypeScript Code Generator for OpenAPI & Swagger
TypeScript support · Plugin system · File management · AST transformation · Custom parsers · Get Started GitHub · How it works · Kubb transforms your OpenAPI specification into production-ready TypeScript code with a powerful plugin system · Plugins · Generate exactly what you need with our extensive plugin library ·
🌐
CodeSignal
codesignal.com › learn › courses › hierarchical-and-structured-data-formats-in-ts › lessons › parsing-json-files-in-typescript-using-nodejs
Parsing JSON Files in TypeScript Using Node.js
Here, filePath is the path to the JSON file with a declared type of string. The fs.readFile function reads the file with UTF-8 encoding, and the callback function handles errors and data processing. ... To parse the JSON data, we use TypeScript's JSON.parse() function, adding type definitions ...
🌐
W3Schools
w3schools.com › js › js_json.asp
W3Schools.com
Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:
🌐
JSON Crack
jsoncrack.com
JSON Crack | Online JSON Viewer - Transform your data into interactive graphs
Format and beautify your JSON data to make it more readable. Validate JSON, YAML, and CSV. Generate TypeScript interface, Golang structs, Rust serde, JSON Schema and more.
🌐
Stripe
docs.stripe.com › webhooks
Receive Stripe events in your webhook endpoint | Stripe Documentation
require 'json' # Replace this endpoint secret with your unique endpoint secret key # If you're testing with the CLI, run 'stripe listen' to find the secret key # If you defined your endpoint using the API or the Dashboard, check your webhook settings for your endpoint secret: https://dashboard.stripe.com/webhooks endpoint_secret = 'whsec_...'; # Using Sinatra post '/webhook' do payload = request.body.read event = nil begin event = Stripe::Event.construct_from( JSON.parse(payload, symbolize_names: true) ) rescue JSON::ParserError => e # Invalid payload status 400 return end # Check that you hav
🌐
Jbeard4
jbeard4.github.io › SCION-CORE › interfaces › __nvm_versions_v8_4_0_lib_node_modules_typedoc_node_modules_typescript_lib_lib_es5_d_.json.html
JSON | typescript
".nvm/versions/v8.4.0/lib/node_modules/typedoc/node_modules/typescript/lib/lib.es5.d" JSON · An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. JSON · parse · stringify · parse(text: string, reviver?: function): ...
🌐
Express
expressjs.com › en › 5x › api.html
Express 5.x - API Reference
You can pass an object as the value parameter; it is then serialized as JSON and parsed by bodyParser() middleware.
🌐
Graphite
graphite.com › guides › json-typescript-conversion
JSON and TypeScript conversion
TypeScript data structures can be converted back to JSON, commonly when sending data from a web application to a server. ... To parse a JSON string in TypeScript, use the JSON.parse() method, ensuring that the output is typed correctly:
🌐
DEV Community
dev.to › maafaishal › safely-use-jsonparse-in-typescript-12e7
Safely use `JSON.parse()` in TypeScript - DEV Community
July 27, 2023 - const jsonString = '{ "title": "Title" }' const jsonValue = JSON.parse(jsonString) // { title: 'Title' } ✅
Top answer
1 of 12
395

TypeScript is (a superset of) JavaScript, so you just use JSON.parse as you would in JavaScript:

let obj = JSON.parse(jsonString);

Only that in TypeScript you can also have a type for the resulting object:

interface MyObj {
    myString: string;
    myNumber: number;
}

let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);

(code in playground)

2 of 12
130

Type-safe JSON.parse

You can continue to use JSON.parse, as TypeScript is a superset of JavaScript:

This means you can take any working JavaScript code and put it in a TypeScript file without worrying about exactly how it is written.

There is a problem left: JSON.parse returns any, which undermines type safety (don't use any).

Here are three solutions for stronger types, ordered by ascending complexity:

1. User-defined type guards

Playground

// For example, you expect to parse a given value with `MyType` shape
type MyType = { name: string; description: string; }

// Validate this value with a custom type guard (extend to your needs)
function isMyType(o: any): o is MyType {
  return "name" in o && "description" in o
}

const json = '{ "name": "Foo", "description": "Bar" }';
const parsed = JSON.parse(json);
if (isMyType(parsed)) {
  // do something with now correctly typed object
  parsed.description
} else { 
// error handling; invalid JSON format 
}

isMyType is called a type guard. Its advantage is, that you get a fully typed object inside truthy if branch.

2. Generic JSON.parse wrapper

Playground

Create a generic wrapper around JSON.parse, which takes one type guard as input and returns the parsed, typed value or error result:

const safeJsonParse = <T>(guard: (o: any) => o is T) => 
  (text: string): ParseResult<T> => {
    const parsed = JSON.parse(text)
    return guard(parsed) ? { parsed, hasError: false } : { hasError: true }
  }

type ParseResult<T> =
  | { parsed: T; hasError: false; error?: undefined }
  | { parsed?: undefined; hasError: true; error?: unknown }

Usage example:

const json = '{ "name": "Foo", "description": "Bar" }';
const result = safeJsonParse(isMyType)(json) // result: ParseResult<MyType>
if (result.hasError) {
  console.log("error :/")  // further error handling here
} else {
  console.log(result.parsed.description) // result.parsed now has type `MyType`
}

safeJsonParse might be extended to fail fast or try/catch JSON.parse errors.

3. External libraries

Writing type guard functions manually becomes cumbersome, if you need to validate many different values. There are libraries to assist with this task - examples (no comprehensive list):

  • io-ts: has fp-ts peer dependency, uses functional programming style
  • zod: strives to be more procedural / object-oriented than io-ts
  • typescript-is: TS transformer for compiler API, additional wrapper like ttypescript needed
  • typescript-json-schema/ajv: Create JSON schema from types and validate it with ajv

More infos

  • Runtime type checking #1573
  • Interface type check with Typescript
  • TypeScript: validating external data
🌐
Zod
zod.dev
Intro | Zod
import * as z from "zod"; const User = z.object({ name: z.string(), }); // some untrusted data... const input = { /* stuff */ }; // the parsed result is validated and type safe! const data = User.parse(input); // so you can use it with confidence :) console.log(data.name); Zero external dependencies · Works in Node.js and all modern browsers · Tiny: 2kb core bundle (gzipped) Immutable API: methods return a new instance · Concise interface · Works with TypeScript and plain JS · Built-in JSON Schema conversion ·
🌐
Biome
biomejs.dev
Biome, toolchain of the web
Biome is a fast formatter for JavaScript, TypeScript, JSX, TSX, JSON, HTML, CSS and GraphQL that scores 97% compatibility with Prettier, saving CI and developer time.
🌐
Microsoft Developer Blogs
devblogs.microsoft.com › dev blogs › typescript › announcing typescript 6.0 beta
Announcing TypeScript 6.0 Beta - TypeScript
1 month ago - In a tsconfig.json, the types field of compilerOptions specifies a list of package names to be included in the global scope during compilation. Typically, packages in node_modules are automatically included via imports in your source code; but for convenience, TypeScript would also include all packages in node_modules/@types by default, so that you can get global declarations like process or the "fs" module from @types/node, or describe and it from @types/jest, without needing to import them directly.