Framework-agnostic JSON:API Serializer

2.6.6 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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));

view raw JSON →