Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support toJSON in Quaternion class #25424

Closed
XorTdsc opened this issue Feb 3, 2023 · 6 comments · Fixed by #25631
Closed

Support toJSON in Quaternion class #25424

XorTdsc opened this issue Feb 3, 2023 · 6 comments · Fixed by #25631

Comments

@XorTdsc
Copy link

XorTdsc commented Feb 3, 2023

Description

Similarly to this request it would be nice to have a clean toJSON serialization for the Quaternion class. Currently the JSON.stringify() results in
{"isQuaternion":true,"_x":0,"_y":0,"_z":0,"_w":1}

Solution

The preferred output should be
{"x":0,"y":0,"z":0,"w":1}

Alternatives

Probably not a viable alternative: Maybe a serialization toolset in a separate class/lib ?

Additional context

No response

@Mugen87
Copy link
Collaborator

Mugen87 commented Feb 3, 2023

I'm fine with adding toJSON() to Quaternion. Especially since Color already has a toJSON() method, too.

@donmccurdy
Copy link
Collaborator

Maybe as an array, like [0, 0, 0, 1]? If we added toJSON on Matrix3 and Matrix4 later they'd be arrays, might as well be consistent.

@Mugen87
Copy link
Collaborator

Mugen87 commented Feb 4, 2023

I'm fine with arrays, too. In the three.js JSON Object/Scene format, matrix and vector properties like the local matrix or the center of a bounding sphere are already serialized as arrays.

@XorTdsc
Copy link
Author

XorTdsc commented Feb 4, 2023

I guess that's fine too, as long as everything is consistent (currently Vector3 does not export as an array)

@epreston
Copy link
Contributor

epreston commented Feb 5, 2023

You can get what you are after by calling toArray on the quaternion.

const quat = new Quaternion(); 
// change rotation
const json = JSON.stringify( quat.toArray() )

When you read it back in use fromArray

const data = JSON.parse( json )
const quatFromJson = new Quaternion().fromArray( data ); 

Vector3 currently has 'to' and 'from' array methods.

You might find it's less than optimal as a storage representation for the same information.

@Mugen87
Copy link
Collaborator

Mugen87 commented Feb 28, 2023

The problem with this suggestion is that you often can't execute such code since the JSON serialization happens indirectly when performing certain operations.

Having a toJSON() implementation solve this as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants