Introduction to Flatted
Flatted is a powerful and efficient JavaScript library for serializing and deserializing JSON objects. It handles complex data structures such as cyclic and circular references without breaking the standard JSON format. In this comprehensive guide, we’ll explore various APIs provided by Flatted and demonstrate their practical usage with detailed code snippets.
Getting Started with Flatted
To start using Flatted, you need to install it via npm:
npm install flatted
API Examples
1. Flatted.stringify()
The Flatted.stringify()
method converts a JavaScript object into a JSON string. This method can handle cyclic references that JSON.stringify()
cannot.
const { stringify } = require('flatted'); const obj = { a: 1, b: 2 }; obj.c = obj; // cyclic reference const jsonString = stringify(obj); console.log(jsonString); // Output: {"a":1,"b":2,"c":"~"}
2. Flatted.parse()
The Flatted.parse()
method parses a JSON string and reconstructs the original JavaScript object, including cyclic references.
const { parse } = require('flatted'); const jsonString = '{"a":1,"b":2,"c":"~"}'; const obj = parse(jsonString); console.log(obj); // Output: { a: 1, b: 2, c: [Circular] }
3. Flatted.toJSON()
The Flatted.toJSON()
method serializes an object to JSON format, handling cyclic references.
const { toJSON } = require('flatted'); const obj = { a: 1, b: 2 }; obj.c = obj; // cyclic reference const jsonString = toJSON(obj); console.log(jsonString); // Output: {"a":1,"b":2,"c":"~"}
4. Flatted.fromJSON()
The Flatted.fromJSON()
method deserializes a JSON string back into an object, restoring cyclic references.
const { fromJSON } = require('flatted'); const jsonString = '{"a":1,"b":2,"c":"~"}'; const obj = fromJSON(jsonString); console.log(obj); // Output: { a: 1, b: 2, c: [Circular] }
App Example Using Flatted
Let’s create a simple Node.js application that uses Flatted to serialize and deserialize objects with cyclic references.
const { stringify, parse } = require('flatted'); const express = require('express'); const app = express(); app.use(express.json()); app.post('/serialize', (req, res) => { const jsonString = stringify(req.body); res.send(jsonString); }); app.post('/deserialize', (req, res) => { const obj = parse(req.body.jsonString); res.send(obj); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); // Test with cyclic JSON object // Run the server and use any API testing tool like Postman to test the serialize and deserialize endpoints
With this application, you can easily send objects with cyclic references to the server and handle their serialization and deserialization using Flatted.
Hash: 4c15d16785318c745de0f42bbe65dd9f848b3295768a4cf75f762bf0381cc44c