Bookshelf: Model to object, similar to .toJSON() ?

Created on 15 Oct 2016  路  4Comments  路  Source: bookshelf/bookshelf

I'm struggling to figure out how to turn a model into a barebones object just containing the current model attributes and joined relations and not keys such as _previousAttributes and changed.

One option is to do JSON.parse(model.toJSON()) but I imagine there is a much better approach than this. :wink:

Most helpful comment

@MarkHerhold I also struggled with this one. It is not as clear in the docs since JSON.stringify is referenced and for me it looked like .toJSON would do the same. Thanks for filing this issue :)

All 4 comments

I'm dumb.

typeof model.toJSON() // 'object'

@MarkHerhold I also struggled with this one. It is not as clear in the docs since JSON.stringify is referenced and for me it looked like .toJSON would do the same. Thanks for filing this issue :)

Clearly the API is wrong, JSON means Javascript Object Notation which is a serialized representation of a Javascript Object, in other words a string. There should be a model.toObj() and model.toJSON() should produce a string.

@GabrielNicolasAvellaneda Actually the .toJSON() method is something natively supported by JSON.stringify(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior

It's not supposed to produce a string. That's the job of JSON.stringify().

Was this page helpful?
0 / 5 - 0 ratings

Related issues

XavierGeerinck picture XavierGeerinck  路  3Comments

cuteboi picture cuteboi  路  4Comments

KieronWiltshire picture KieronWiltshire  路  3Comments

chimmelb picture chimmelb  路  4Comments

Oxyrus picture Oxyrus  路  4Comments