JSON getter / setters for Session variables
- NOTE: This package is not maintained anymore.
- If you want to help, please reach out to [email protected]
Reactive JSON getters / setters for Session variables
Meteor 0.9+
meteor add gwendall:session-json
Prior to Meteor 0.9
mrt add session-json
Let's create a vanilla Session value.
var json = {
some: {
nested: "value"
}
};
Session.set("json", json);
Let's try to get / set those nested properties.
Session.get("json.some.nested")
// > undefined
Session.set("json.some.nested", "other value")
Session.get("json")
// > {
some: {
nested: "value" // Unchanged!
}
}
Trying to access the "some.nested" property through Session.get("json.some.nested") returns "undefined", and trying to change this property through Session.set("json.some.nested", "other value") would create a new Session variable with the "json.some.nested" key, since Sessions (and ReactiveDict objects in general) in Meteor are simple key / value stores.
Session.getJSON("json.some.nested");
// > "value"
Session.setJSON("json.some.nested", "other value")
Session.get("json")
// > {
some: {
nested: "other value"
}
}
Meteor Sessions can't store arrays directly, but can store objects containing arrays. So doing the following thing won't work as you may want.
Session.setJSON("someArray[0]", "first array value!");
Session.getJSON("someArray");
// > undefined
Session.getJSON("someArray[0]");
// > "first array value!"
In this case, it would create a Session variable with the key "someArray[0]" and store its value as a string.
To set / edit an element in an array, set it as a nested property.
Session.setJSON("someProperty.someArray[0]", "first array value!");
You can then access this array.
Session.getJSON("someProperty.someArray");
// > ["first array value!"]
Enjoy!