Deviopath › Node.js

Safe JSON Parse

Easy · JSON

JSON.parse throws on invalid input. In a Node server, a client sending a broken request body should not crash your code.

Write a function safeParse(text) that never throws:

- valid JSON: return { ok: true, value } with the parsed value

- invalid JSON: return { ok: false, error: "Invalid JSON" }

Next: Is It a JSON Request?