Registry / serialization / json-api-serializer

json-api-serializer

JSON →
library2.6.6jsnpmunverified

json-api-serializer is a versatile JavaScript library for Node.js and browsers, designed to serialize JavaScript objects into JSON:API 1.0 compliant documents and deserialize JSON:API documents back into standard JavaScript objects. The current stable version is 2.6.6. It maintains an active development cycle, frequently releasing minor updates and bug fixes. Key differentiators include its framework-agnostic nature, extensive configuration options for defining complex relationships, links, and metadata, and support for both serialization and deserialization processes. It allows for fine-grained control over attribute whitelisting/blacklisting, case conversion, and custom logic for handling relationships, making it adaptable to various JSON:API implementations.

npm install json-api-serializer
INSTALL
IMPORT
SIG · JSON-API-SERIALIZE
J
json-api-serializer
serializationjavascriptv2.6.6
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

JSONAPISerializer
✓ import JSONAPISerializer from 'json-api-serializer';
✗ const JSONAPISerializer = require('json-api-serializer');
While the documentation often shows CommonJS `require`, ESM default import is the standard for modern Node.js and browser environments. The package exports the constructor directly as the default export.
Serializer (instance)
✓ import JSONAPISerializer from 'json-api-serializer'; const serializer = new JSONAPISerializer();
✗ import { Serializer } from 'json-api-serializer';
The `Serializer` is an *instance* created from the `JSONAPISerializer` class, not a direct named export. Attempting to import `Serializer` directly will result in an undefined module member error.

This quickstart demonstrates how to initialize `json-api-serializer`, register custom schemas for 'user' and 'post' types with relationships, and then perform both serialization of a JavaScript object into JSON:API format and deserialization of a JSON:API document back into a plain object. It highlights `id` customization, blacklisting attributes, and defining relationship logic.

import JSONAPISerializer from 'json-api-serializer'; // 1. Initialize the serializer const serializer = new JSONAPISerializer(); // 2. Register a 'user' type serializer.register('user', { id: 'uuid', // Use 'uuid' as the ID field instead of default 'id' blacklist: ['passwordHash'], relationships: { posts: { type: 'post', // The type of the related resource links: { self: (data, extraData) => `/users/${data.uuid}/relationships/posts` } }, comments: { type: 'comment', alternativeKey: 'commentIds' // Use 'commentIds' if 'comments' relationship key is missing } }, links: { self: (data) => `/users/${data.uuid}` } }); // 3. Register a 'post' type serializer.register('post', { attributes: ['title', 'content', 'createdAt'], relationships: { author: { type: 'user', deserialize: (data) => data.id // Custom deserialization for author } } }); // Example Data const userData = { uuid: 'u123', name: 'Alice', email: 'alice@example.com', passwordHash: 'hashedpassword', posts: [{ id: 'p1', title: 'My First Post' }, { id: 'p2', title: 'Another Post' }], commentIds: ['c1', 'c2'] }; const postData = { id: 'p1', title: 'My First Post', content: 'Hello World!', createdAt: new Date().toISOString(), author: { id: 'u123' } }; // 4. Serialize data const serializedUser = serializer.serialize('user', userData); console.log('Serialized User:', JSON.stringify(serializedUser, null, 2)); // 5. Deserialize data (requires a full JSON:API document) const jsonApiDoc = { data: { type: 'user', id: 'u123', attributes: { name: 'Alice', email: 'alice@example.com' }, relationships: { posts: { data: [ { type: 'post', id: 'p1' }, { type: 'post', id: 'p2' } ] } } }, included: [ { type: 'post', id: 'p1', attributes: { title: 'First Post Title' } }, { type: 'post', id: 'p2', attributes: { title: 'Second Post Title' } } ] }; const deserializedData = serializer.deserialize('user', jsonApiDoc); console.log('Deserialized Data:', JSON.stringify(deserializedData, null, 2));
Debug
Known issues
breakingOlder versions (prior to 2.4.1) could enter an infinite loop when deserializing data with circular references, leading to a 'Maximum call stack size exceeded' error.
fix
Upgrade to `json-api-serializer` version 2.4.1 or higher. Ensure your data structures are not unintentionally circular, especially when defining `relationships` where an object might reference itself or an ancestor.
affects: <2.4.1
gotchaAttempting to serialize or deserialize a relationship for a type that has not been explicitly registered with `serializer.register()` will lead to errors.
fix
Always ensure all related `type`s specified in `relationships` options are registered before performing serialization or deserialization operations. For example, if a 'user' has 'posts', both 'user' and 'post' types must be registered.
affects: >=2.0.0
gotchaDeserialized data might have `undefined` `id` fields if the input JSON:API document lacks an `id` for a resource, which can cause issues if your application expects all resources to have an `id`.
fix
Upgrade to version `2.6.6` or higher to correctly handle cases where `id` might be missing in the input. Alternatively, implement defensive checks in your application code for `id` presence after deserialization.
affects: <2.6.6
deprecatedThe behavior regarding the `included` array in serialized output has been adjusted. Previously, the `included` array might have been present even if the input had no attributes. This is now fixed to be more compliant.
fix
This was a fix in `v2.6.4`. Be aware that if your application relied on the presence of an `included` array in older versions even when no relationships had attributes, you might need to adjust your expectations or post-processing logic when upgrading.
affects: <2.6.4
Errors
Common errors & fixes
RangeError: Maximum call stack size exceeded
Circular references in the data being serialized or deserialized, leading to an infinite recursion.
fix
Refactor your data to break circular dependencies, or ensure you are using `json-api-serializer` version 2.4.1 or higher which includes fixes for preventing circular deserialization.
Error: Relationship '...' is not registered.
Attempting to serialize or deserialize data that contains a relationship to a type ('...') which has not been registered with the `serializer.register()` method.
fix
Register all resource types involved in relationships using `serializer.register('type', options)` before performing any serialization or deserialization operations that involve those relationships.
TypeError: Cannot read properties of undefined (reading 'id')
This error can occur during deserialization when an unregistered relationship is encountered, or when a relationship's `deserialize` function attempts to access `data.id` on an `undefined` or malformed relationship object.
fix
Ensure all relationships are properly registered. Review the `deserialize` function for relationships in your `serializer.register()` options to handle cases where `data` might be `null` or `undefined`, especially for optional relationships. Upgrade to `v2.6.5` or higher which fixes errors when deserializing unregistered relationships.
Upgrade
Version history
2.6.6latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
8 hits · last 30 days
node
8
Resources
json-api-serializer — npm install json-api-serializer · libregistry