I am working with nodejs and using module named "JSONAPI-Serializer" for serialization and deserialization purpose.
I am able to serialize the objects without any issue but not able to deserialize the same serialized data.
So,using below code I am able to serialize the data:
root#test$: node test.js
var data = [{ id: 1},{ id: 2 }];
var JSONAPISerializer = require('jsonapi-serializer').Serializer;
var UserSerializer = new JSONAPISerializer('id', {"test":"me"});
var users = UserSerializer.serialize(data);
console.log("Serialized:\n", UserSerializer.serialize(data));
Below is the generated result for the same:-
Serialized:
{ data: [ { type: 'ids', id: '1' }, { type: 'ids', id: '2' } ] }
But on deserialization, I am not able to make it work trying to perform the same example as documented in document of "JSONAPI-Serializer".
Can anyone tell me the way to deserialize the above data using "JSONAPI-Serilizer" ?
You're missing your deserialization code. Here is mine that works.
The issue what missing "attributes" option for serializer.
var data = [{ id: 1},{ id: 2 }];
var JSONAPISerializer = require('jsonapi-serializer').Serializer;
var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;
var UserSerializer = new JSONAPISerializer('id', {attributes: ['id']});
var users = UserSerializer.serialize(data);
console.log(users)
var UserDeserialize = new JSONAPIDeserializer();
UserDeserialize.deserialize(users)
.then(a => console.log(a))
Related
I am developing a CLI using Enquirer. I want user of the CLI to write javascript on a json.
So, i want something like this :
Create a Rule on the the data
const model = {
reviews: {
'5': [
{
customerId: 'A2OKPZ5S9F78PD',
rating: '5',
asin: 'asin2',
reviewStatus: 'APPROVED',
reviewId: 'R379DKACZQRXME',
},
],
'4': [
{
customerId: 'A2OKPZ5S9F78PD',
rating: '4',
asin: 'asin2',
reviewStatus: 'APPROVED',
reviewId: 'R379DKACZQRXME',
},
],
},
entityType: 'LIVE_EVENT',
entityId: 'event2',
};
Then user writes the rule.
Object.values(model.reviews).forEach(reviews =>
(reviews as any).forEach(review => {
if (parseInt(review.rating) < 3 && attributes.reviewId.Value.includes(review.reviewId)) {
output.push({
exceptionName: `Customer ${review.customerId} left a review ${review.reviewId} with rating ${review.rating}`,
});
}
})
);
While writing this rule, Since it is on the above json model, I want to provide autocomplete options on javascript and validate if it is correct javascript.
Is there a way to do this ?
If I'm understanding your question correctly, it sounds like you want to take the model object and write it to a JSON file.
If this is your goal, simply do the following:
import { writeFileSync } from "fs";
// Define the model
const model: any = { foo: bar };
// Transform the model object to JSON
const modelJSON: string = JSON.stringify(model, null, 4); // Indents the JSON 4-spaces
// Write the modelJSON to `model.json`
writeFileSync("./model.json", modelJSON);
The above is TypeScript, but the standard JavaScript version is basically the same. Make sure you add #types/node to your package.json file if you're using TypeScript - hope this helps!
Im trying to separate out the functionality of my model and the data so ive created a separate json file with a basic table
when my model builds it creates an object and i need it to create a value in it based on a value coming in:
{
"1":"apple",
"2":"banana",
"3":"orange",
"4":"grape"
}
async save (xmlOrder) {
let customerOrder = {
ID: xmlOrder.ID,
Name: xmlOrder.Name ,
ItemCode: xmlOrder.ItemCode ,
Fruit: (This set by referencing the json, based on the Item code coming in above)enter code here
}
You can import that json object in file where you're having your model, than based on input to function you can get value out of object.
let obj = {"1":"apple","2":"banana","3":"orange","4":"grape"}
function save (xmlOrder) {
let customerOrder = {
ID: xmlOrder.ID,
Name: xmlOrder.Name ,
ItemCode: xmlOrder.ItemCode ,
Fruit: obj[xmlOrder.ItemCode] || 'Not in list',
}
return customerOrder
}
console.log(save({ID:33,Name:'Name',ItemCode:'2'}))
console.log(save({ID:303,Name:'Name1',ItemCode:'21'}))
I use Angular 6 and smart table :
https://akveo.github.io/ng2-smart-table/#/.
Everything works just fine, till I try to change data from static to dynamic :
This works and shows everything in table :
source: LocalDataSource = new LocalDataSource();
data = [{
id: 1,
Customer: 'UK LTD',
Name: 'Mark Poll',
Code: '84615A',
PostalCode: 'U48K46',
Date: '09/19/2018',
},
];
this.source.load(this.data);
and this doesnt :
data1 = [];
source: LocalDataSource = new LocalDataSource();
getArray() {
this.afDatabase.list('/imones').valueChanges().subscribe(res => {
this.data1 = res;
console.log(this.data1)
})
}
this.source.load(this.data1);
Outputs are equal :
What's wrong with that and maybe somebody was facing this problem ?
I did not work with Firebase or ng2-smart-table before, but it should work if you move your loading of the data-source within the subscribe.
source: LocalDataSource = new LocalDataSource();
getArray() {
this.afDatabase.list('/imones').valueChanges().subscribe(res => {
this.source.load(res);
})
}
I'm trying to save an array of objects to my mongo db in one save. I'd like to store each new object into a temporary array first, then send it to the server.js via an ajax post request. But each time it gets to the server, the data becomes just one giant object, and not an array of objects. Is what I'm trying to do possible with Mongo, or am I missing something? Here's my code below.
SCHEMA
var capsuleSchema = new mongoose.Schema({
qa: [{
type: mongoose.Schema.Types.ObjectId, ref: 'Question',
question: String,
answer: String
}],
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User'},
date_of_return: Date,
created_at: { type: Date, default: Date.now }
});
var Capsule = mongoose.model('Capsule', capsuleSchema);
module.exports = Capsule;
APP.JS
var temp_id = id;
var temp_q = quest;
var temp_ans = $('#response').val();
var tempQA = {
id: temp_id,
question: temp_q,
answer: temp_ans
};
saveQuestion(tempQA);
var saveQuestion = function(tempQA) {
answeredQuestions.push(tempQA);
}
var capsuleData = {
questions: answeredQuestions
}
newCapsule(capsuleData);
var newCapsule = function(capsuleData) {
$.ajax({
url: "http://localhost:3000/capsules",
method: "POST",
dataType: 'json',
data: capsuleData
}).done(function(data){
// returns "capsule creation complete"
});
}; // end newCapsule
SERVER.JS
app.post('/capsules', function(req, res) {
var qa_array = [];
var capsule = new Capsule({
qa: req.body.questions,
user: req.cookies.loggedinId,
});
capsule.qa.push(req.body)
capsule.save( function(err, capsule) {
if (err) {
console.log(err);
res.statusCode = 503;
} else {
res.send(capsule);
}; // end if/else
}); // end save
}); // end post time-capsule
UPDATE:
I accidentally put the newCapsule(capsuleData) in the capsule object.--fixed.
I think the problem is in the ajax request. When the Array of objects goes through and gets to the server.js it gets reformatted into and array of one object containing array-innumerated, key:value pairs as strings even before I do anything with it on the server side. ("ie: 'questions[0][id]' : '12345', 'questions[0][question]' : 'how are you?'" etc.
I need it to stay as an array of objects though.
If you want to save multiple documents, try db.collection.insert
Check it out
The below code is not syntactically correct. capsuleData isn't a function its an object literal.
var capsuleData = { questions: answeredQuestions newCapsule(capsuleData); }
The below code attaches a method to the object. You also need to include Capsule() as a javascript function that is accessible so new Capsule() can create the javascript object. But that is still creating an object and not an array. You need to create the array client side and then pass it to the server to be processed.
var capsuleData = { questions: answeredQuestions,
anObjectMethod : new Capsule(capsuleData); }
Review this for more in-depth help https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
My problem is that I am just starting out with Backbone.js and are having trouble wrapping my head around a complex problem. I want to save a form that have infinite fields, and some of the fields also needs to have infinite options. I'm just worried I might have started at the wrong end with a JSON response, instead of building the models/collections first. Here is a short pseudocode of what I try to achieve.
id:
parent: <blockid>
fields: array(
id:
title:
helpertext
options: array(
id:
type:
value:
)
)
Currently I am working with a faked JSON response from the server, which I built from scratch, and now I want to divide it into models and collections on the client side.
//Fake a server response
var JSONresponse = {
"formid":"1",
"fields":[
{
"fieldid":"1",
"title":"Empty title",
"helper":"Helper text",
"type":"radio",
"options":[
{
"optionid":"1",
"value":"Empty option.."
},
{
"optionid":"2",
"value":"Empty option.."
}
]
},
{
// fieldid2
}
]
};
The idea is to add fields as I see fit, and then if the field type is radio/checkbox/ul/ol there must also be an "options" array within the field.
My work so far:
var app = {};
app.Models = {};
app.Collections = {};
app.View = {};
app.Models.Option = Backbone.Model.extend({
});
app.Collections.Options = Backbone.Collection.extend({
model: app.Models.Option
});
app.Models.Field = Backbone.Model.extend({
options: new app.Collections.Options()
});
app.Collections.Fields = Backbone.Collection.extend({
model: app.Models.Field
});
app.Models.Form = Backbone.Model.extend({
formid : "1",
fields: new app.Collections.Fields(),
initialize: function() {
}
});
How do I split up my JSON response into all these models and collections?
(Perhaps I should re-evaluate my approach, and go for something like form.fieldList and form.optionList[fieldListId] instead. If so, how would that look like?)
Edit: Here is a little jsfiddle after many fixes, but I still don't really know how to make the inner options list work.
The easiest solution would be using Backbone Relational or Backbone Associations.
The documentation should be enough to help you get started.
If you don't want to use a library you could override the parse function on the Form model.
app.Models.Form = Backbone.Model.extend({
defaults: {
fields: new app.Collections.Fields()
},
parse: function(response, options) {
return {
formid: response.formid,
fields: new app.Collections.Fields(_.map(response.fields, function(field) {
if (field.options) {
field.options = new app.Collections.Options(field.options);
}
return field;
}))
};
}
});
Now if you fetch a form from the server, the response will be parsed into an object graph of models and collections.
form.get('fields') will return an app.Collections.Fields collection. form.get('fields').first().get('options') will return an app.Collections.Options collection, if any options exist.
Also, you could create the form model like this:
var form = new app.Models.Form(JSONresponse, {
parse: true
});
This would result in the same object structure.
It's quite hard to handle the case of nested models and collections right in plain Backbone.
Easiest way of handling this will be something like this:
var Option = Nested.Model.extend({
idAttribute : 'optionid',
defaults : {
optionid : Integer
value : ""
}
});
var Field = Nested.Model.extend({
idAttribute : 'fieldid',
defaults : {
fieldid : Integer,
title : "",
helper : "",
type : "radio",
options : Option.Collection
}
});
var Form = Nested.Model.extend({
idAttribute : 'formid',
defaults : {
formid: Integer,
fields: Field.Collection
});
https://github.com/Volicon/backbone.nestedTypes
And that's it. Yep, you'll get direct access to the attributes as free bonus, just form.fields.first().options.first().value, without that get and set garbage.