Structure
Structure v1
Structure v1
  • Introduction
  • Schema concept
    • Shorthand and complete type descriptor
    • Circular reference
    • Nullable attributes
  • Coercion
    • Primitive type coercion
    • Arrays coercion
    • Generic coercion
    • Recursive coercion
    • Observations
  • Validation
    • String validations
    • Number validations
    • Boolean validations
    • Date validations
    • Array validations
    • Attribute reference
    • Nested validations
    • Validate raw data
  • Strict mode
  • Cloning an instance
  • Serialization
  • Contributing
  • License
  • GitHub
Powered by GitBook
On this page

Was this helpful?

Serialization

PreviousCloning an instanceNextContributing

Last updated 5 years ago

Was this helpful?

It's possible to obtain a serialized object of a Structure using the method toJSON(). This method is also compliant with the specification, so you can use it to serialize your object too.

Important:

  • Be aware that toJSON() will return an object, not the JSON in form of a string like JSON.stringify() does

  • Refer to the specification to see how dates will be serialized by JSON.stringify

  • Refer to to check how nullables are going to be returned on Serialization

const Book = attributes({
  name: String
})(class Book { });

const User = attributes({
  name: String,
  birth: Date,
  books: {
    type: Array,
    itemType: Book
  }
})(class User { });

const user = new User({
  name: 'John Something',
  birth: new Date('10/10/1990'),
  books: [
    new Book({ name: 'The name of the wind' }),
    new Book({ name: 'Stonehenge' })
  ]
});

user.toJSON(); /* {
  name: 'John Something',
  birth: new Date('10/10/1990'),
  books: [
    { name: 'The name of the wind' },
    { name: 'Stonehenge' }
  ]
}
*/

JSON.stringify(user)); // {"name":"John Something","birth":"1990-10-10T03:00:00.000Z","books":[{"name":"The name of the wind"},{"name":"Stonehenge"}]}
JSON.stringify()
Date#toJSON
Dealing with nullable attributes