JSORM.db.parser.json
From Jsorm
Overview
Parser to convert between JSON as a string and JavaScript objects (POJSO) suitable for jsormdb records. Additionally parses metadata passed along with the JSON data.
Usage
The json parser does not require any configuration at instantiation time. However, it can be configured with a single element, a JavaScript object, passed at instantiation. The only relevant elements are:
- id: The name of the field within the records of the loaded data to be used as the unique ID field. If a different value is present in the actual metadata of the loaded information, it will override this field. Loaded metadata takes precedent, which is logical. We always assume the remote data source knows more about its data than we do.
- root: The element within the top-level of the JSON that contains an array of records, which is the data. Thus, the JSON can have many elements, but the one whose name matches the value of root will be treated as the root of the records. If a different value is present in the actual metadata of the loaded information, it will override this field. Loaded metadata takes precedent, which is logical. We always assume the remote data source knows more about its data than we do.
The metadata can be overridden from within the sent data by placing an element named "meta" within the JSON. Elements of meta will override elements configured at instantiation. However, these changes are relevant only for this load. The defaults remain as passed at instantiation.
// set up a json parser var config = { root: "recs", id: "uid" } var parser = JSORM.db.parser.json(config);
The above parser will decode the following JSON, using the "uid" field as the unique identifier, and the data from "recs":
{ test: "My foo", recs: [{name: "John", uid: 200, eid: 600},{name: "Jill", uid: 300, eid: 700}] others: [{name: "Karl", uid: 200, eid: 600},{name: "Kathy", uid: 300, eid: 700}] }
If the following JSON is provided, then the records are taken from "others" and the "eid" field is used as the unique identifier:
{ test: "My foo", meta: {root: "others", id: "eid"}, recs: [{name: "John", uid: 200, eid: 600},{name: "Jill", uid: 300, eid: 700}] others: [{name: "Karl", uid: 200, eid: 600},{name: "Kathy", uid: 300, eid: 700}] }
Finally, if the entire JSON is just an array, then the entire element will be treated as records, and the ID field will be the default as configured at instantiation time. It is important to note that some JSON parsers do not accept as valid JSON anything other than an actual object. Thus, the below will be treated as invalid.
[{name: "Karl", uid: 200, eid: 600},{name: "Kathy", uid: 300, eid: 700}]
