I have a simple set of JSON data that I am pulling from a local file and loading into a datatable
Using YUI, how can I filter the response of this request to match only the data that is relevant to the request data?
EDIT: improper formatting on first post
YUI().use('aui-datatable', 'datatable-sort', 'aui-io-request', 'aui-tabview', 'datasource-io',
function(Y) {
var columns = [{
key : 'id',
sortable : true
}, {
key : 'name',
sortable : true
},{
key : 'price',
sortable : true
}];
var dataTable = new Y.DataTable({
columns : columns
}).render("#searchResultsTab");
var node = Y.one('#searchButton');
var criteria = document.getElementById("searchCriteria");
node.on(
'click', //on Search..
function(){
dataSource = new Y.DataSource.IO({source:'mydata.json'});
request = document.getElementById("searchBox").value;
dataSource.sendRequest({
on: {
success: function(e){
var response = e.data.responseText;
jdata = Y.JSON.parse(response);
dataTable.set('data', jdata.info); //setting table data to json response
},
failure: function(e){
alert(e.error.message);
}
}
});
}
);
new Y.TabView(
{
srcNode: '#searchResultsContainer'
}
).render();
});
mydata.json
{"info" : [
{"id": 1,"name": "A green door","price": 12.50 },
{"id": 2,"name": "A blue door","price": 10.50 },
{"id": 3,"name": "A red door","price": 8.50 }
}
In your on success method filter your response data before setting the datatable data source. Here is an example of model list filtering: http://yuilibrary.com/yui/docs/model-list/#filtering-models
Related
I am trying to make a post request with the MongoDB document returned from find query, as the request body in NodeJS.But on the server I'm getting the Error : Invalid JSON. Below is the document that I'm trying to POST
{
"_id" : ObjectId("5739a6bf3f1b41477570dc89"),
"taskCount" : 2,
"study" : "cod",
"phase" : "mansa2",
"rhimeTaskId" : "5739a6bec4567f6e737fd3db",
"recordId" : "5726f3cfc4567f6e737fc3ab",
"recordStudy" : "codstudy",
"recordPhase" : "mansa2",
"recordLanguage" : "Punjabi",
"recordScript" : "Latin",
"_state" : "CodingComplete",
"tasks" : [
{
"physician" : ObjectId("5739a6bd3f1b41477570dc78"),
"stage" : "Coding",
"result" : {
"cod" : "C15",
"feedback" : {
"narrativeLength" : "Adequate",
"positiveSymptomsIncluded" : "Only Positive",
"certainty" : "High"
},
"keywords" : [
"52 yr male, died of food pipe cancer, suffered pain upper abdomen, investigated,FNAC confirmed Cancer, Put on Chemotherapy, multiple cycles, died at home, had fever with chills occasionally"
]
}
},
{
"physician" : ObjectId("5739a6bd3f1b41477570dc79"),
"stage" : "Coding",
"result" : {
"cod" : "C15",
"feedback" : {
"narrativeLength" : "Inadequate",
"positiveSymptomsIncluded" : "Only Positive",
"certainty" : "High"
},
"keywords" : [
"severe pain abdomen, ultrasonography revealed food pipe cancer, chemotherapy given, died"
]
}
}
],
"__v" : 2
}
and here is the code that I wrote to make the POST request
var MongoClient = require('mongodb').MongoClient;
var request = require('request');
var assert = require('assert');
var cmeprovisioning= 'mongodb://localhost:27017/cmeprovisioning';
MongoClient.connect(cmeprovisioning, function(err, db) {
assert.equal(null, err);
var count=0;
console.log("Connected to cmeprovisioning");
var cursor =db.collection('rhimeReport').find(
{"study":"cod","phase":"mansa2","recordStudy":"codstudy",
"recordPhase":"mansa2","_state":"CodingComplete"
});
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
count=count+1;
request({url: "http://cme.host.net:8081/cme-provisioning/update",
method: "POST",json: true,
headers: {"content-type": "application/json"},
json: doc
},function(e,r,b){
console.log("POST Error "+count+" "+e)
console.log("POST Response "+count+" "+r)
console.log("POST BODY "+count+" "+b)
});
} else {
console.log("Some Error : "+err)
}
});
});
I also tried using JSON.stringify(doc), but still got the Invalid JSON error. Is there a way I can use mongo document returned by the find query and convert it to JSON to make the POST request.
I think those ObjectID is what making it an invalid JSON document.
Here's the actual answer:
If you want to convert a mongo object to JSON object.
There's a utility method in every mongo object toJSON
So you can simply do mongoResponseObject.toJSON() on the response object.
e.g.
Products.findById(id).then(res => {
const jsonRes = res.toJSON();
// Here jsonRes is JSON
})
Alternatively you can directly get the JSON object by using the .lean() like this.
Products.findById(id).lean().then(res => {
// Here res is JSON
})
you need to convert object id to string ie.
var result = {
"_id": ObjectId("5739a6bf3f1b41477570dc89"),
"taskCount": 2,
"study": "cod"
};
//now convert to string
result=result._id.toString();
//now you can use the result
Try this,
var cursor =db.collection('rhimeReport').find(
{"study":"cod","phase":"mansa2","recordStudy":"codstudy",
"recordPhase":"mansa2","_state":"CodingComplete"});
cursor.toString();
......
Hope this help.
Try this in robomongo
var cursor = db.getCollection('X').find({},{})
while(cursor.hasNext()) {
print(JSON.stringify(cursor.next()))
}
Hello guys i have a problem with displaying my pie chart, when i try to add more data into the pie chart this error occurs, i need your expertise on this matter
this is my controller code. and the error message is
[50053] - Incomplete dimensions binding
onInit: function() {
this._setupSelectionList();
// 2.Create a JSON Model and set the data
var oModel = new sap.ui.model.json.JSONModel("http://lssinh000.sin3.sap.corp:8000/SAP_LE/lionExpress/Volunteer/Services/request.xsjs");
var oVizFrame = this.getView().byId("idpiechart");
// 3. Create Viz dataset to feed to the data to the graph
var oDataset = new sap.viz.ui5.data.FlattenedDataset({
dimensions : [{
name : 'Status',
value : "{Status}",
name : 'StartDate',
value : '{StartDate}'
}],
measures : [{
name : 'reqID',
value : '{reqID}',
},],
data : {
path : "/Status"
}
});
oVizFrame.setDataset(oDataset);
oVizFrame.setModel(oModel);
// 4.Set Viz properties
oVizFrame.setVizProperties({
title:{
text : "Delivery Summary"
},
plotArea: {
colorPalette : d3.scale.category20().range(),
drawingEffect: "glossy"
}});
var feedSize = new sap.viz.ui5.controls.common.feeds.FeedItem({
'uid': "size",
'type': "Measure",
'values': ["reqID"]
}),
feedColor = new sap.viz.ui5.controls.common.feeds.FeedItem({
'uid': "color",
'type': "Dimension",
'values': ["Status"]
}),
feedValue = new sap.viz.ui5.controls.common.feeds.FeedItem({
'uid': "value",
'type': "Dimension",
'values': ["StartDate"]
});
oVizFrame.addFeed(feedSize);
oVizFrame.addFeed(feedColor);
oVizFrame.addFeed(feedValue);
//this.getView().byId("idPopOver").connect(oVizFrame.getVizUid());
},
In the dataset, the name attribute has to be same as in the values arrays of the feeds.
I want to define my mongoose schema from JSON file. This is my JSON file structure:
{
"default": [
{
"item": "productTitle",
"label": "Product Title",
"note": "e.g Samsung GALAXY Note 4",
"type": "text",
"required": "Product Name cannot be blank..."
},
{
"item": "productCode",
"label": "Product Code",
"type": "text",
"required": "Product Code cannot be blank..."
}
]}
This is my node.js model:
// Load the module dependencies
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var fs = require('fs');
var file = __dirname + '/product.server.model.json';
// Read the json file
fs.readFile(file, 'utf8', function (err, data) {
data = JSON.parse(data);
var productJson = {};
for(var i = 0; i < data.default.length; i++) {
productJson[data.default[i].slug] = {
type: 'String',
required: data.default[i].required,
default: '',
trim: true
}
}
});
// Define a new 'ProductSchema'
var ProductSchema = new Schema(
// Here I want to put JSON Data 'productJson'
);
// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);
I tried every possible way to define mongoose schema from JSON data 'productJson'. But unless I pre-define my mongoose schema, it is not working. Is there any way to define mongoose schema from JSON data in my model? Any suggestion please?
fs.readFile is an asynchronous function which means that it returns immediately and then later provides its results to the caller via the callback function that you provide as the third parameter.
As such, you need to hold off on using productJson until its populated within that callback. That means moving your schema and model creation inside the callback as well.
fs.readFile(file, 'utf8', function (err, data) {
data = JSON.parse(data);
var productJson = {};
for(var i = 0; i < data.default.length; i++) {
// Changed .slug to .item here as I don't see slug in the JSON
productJson[data.default[i].item] = {
type: 'String',
required: data.default[i].required,
default: '',
trim: true
}
}
// Define a new 'ProductSchema'
var ProductSchema = new Schema(productJson);
// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);
});
Another alternative you can use here is to use the synchronous fs.readFileSync method to read the file instead. This is helpful in startup/initialization cases like this where your application as a whole shouldn't proceed until this file is processed.
var data = fs.readFileSync(file, 'utf8');
data = JSON.parse(data);
var productJson = {};
for(var i = 0; i < data.default.length; i++) {
// Changed .slug to .item here as I don't see slug in the JSON
productJson[data.default[i].item] = {
type: 'String',
required: data.default[i].required,
default: '',
trim: true
}
}
// Define a new 'ProductSchema'
var ProductSchema = new Schema(productJson);
// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);
I have multiple json Objects
json1 = [
{'category_id':1,'name':'test1' },
{'category_id':1,'name':'test2' },
{'category_id':1,'name':'test3' },
{'category_id':2,'name':'test2' },
{'category_id':3,'name':'test1' }
];
json2 = [{'category_id':1,'type':'test1'}];
json3 = [
{'category_id':1,'color':'black'},
{'category_id':2,'color':'black'},
{'category_id':3,'color':'white'}
];
I am expecting output like this
final = [
{'category_id':1,'name':'test1','type':'test`','color':'black' },
{'category_id':1,'name':'test2','type':'test`','color':'black' },
{'category_id':1,'name':'test3','type':'test`','color':'black' },
{'category_id':2,'name':'test2','color':'black' },
{'category_id':3,'name':'test1','color':'white' }
];
As i have long json object. Looping is good idea or not ? Does there is any inbuilt function for doing the same.
Using underscore you can achieve it via:
Demo Fiddle
var jsons = [json1, json2, json3];
var final = {};
// merge all data
_.each(jsons, function (jsonArr) {
_.each(jsonArr, function (json) {
final[json.category_id] = _.extend({}, final[json.category_id], json);
});
});
// map it back onto json1
var finalArr = _.map(json1, function (json) {
return final[json.category_id];
});
console.log(finalArr);
Final value of finalArr:
Here is how you can do the same in plain javascript. :)
var final = {};
var jsons = [json1, json2, json3];
for(var i=0;i<jsons.length;i++){
final[i]=jsons[i];
}
Fiddle
EDIT:
Well, you will have to do it programmatically!
I have a complex JSON Object like this:
var requestData = { __batchRequests: [ { __changeRequests: [
{ requestUri: "Customers", method: "POST", headers: { "Content-ID": "1" }, data: {
CustomerID: 400, CustomerName: "John"
} }
] } ] };
I am trying to do two things:
Declare this object but with the variable data empty
With a loop, add items dynamically to the data object,
How can I do it?
This isn't too complex an object. And it isn't JSON until it's converted into a string.
Right now, it's just plain-ol' JS objects and arrays.
Breaking that down into its elements might look like this:
var requestData = {};
requestData.__batchRequests = [];
requestData.__batchRequests[0] = {};
requestData.__batchRequests[0].__changeRequests = [];
requestData.__batchRequests[0].__changeRequests[0] = {};
requestData.__batchRequests[0].__changeRequests[0].requestUri = "Customers";
requestData.__batchRequests[0].__changeRequests[0].method = "POST";
requestData.__batchRequests[0].__changeRequests[0].headers = { "Content-ID" : "1" };
requestData.__batchRequests[0].__changeRequests[0].data = {};
Aside from the repeats, what do you see?
Personally, I see that __changeRequests[0] is an object as simple as:
var changeRequest = {
requestUri : "Customers",
method : "POST",
headers : { "Content-ID" : "1" },
data : {}
};
I also see that I can just push that onto my array of change requests:
requestData.__batchRequests[0].__changeRequests.push(changeRequest);
Right?
I also know that my changeRequest variable still points to the one that I just added to the array, and whatever I change on the object will show up as changed in the array's reference to the object, too:
changeRequest.data.CustomerName = "Bob";
changeRequest.data.CustomerID = "204";
requestData.__/*...*/changeRequests[0].data.CustomerName; // Bob
So how about writing yourself some helper-functions?
function extend (obj, additions) {
var key;
for (key in obj) { if (additions.hasOwnProperty(key)) {
obj[key] = additions[key];
}
}
function makeChangeRequest (url, method, headers, data) {
var request = {
requestUri : url,
method : method,
headers : {},
data : {}
};
extend(request.headers, headers);
extend(request.data, data);
return request;
}
function getBatch (num) { return requestData.__batchRequests[num]; }
var changeReq = makeChangeRequest("Customers",
"POST",
{ "Content-ID" : "1" },
{ CustomerName : "Bob", CustomerID : "2012" });
var batch = getBatch(0);
batch.__changeRequests.push(changeReq);
If you want to add more data to changeReq.data later:
extend(changeReq.data, { Address : "33 Nowhere Rd.", City : "Splitsville" });
For the first part of your question, you can initialize data with an empty associative array:
var requestData = { __batchRequests: [ { __changeRequests: [
{ requestUri: "Customers", method: "POST", headers: { "Content-ID": "1" }, data: {} }
] } ] };
This next part assumes, perhaps incorrectly, that you can use jQuery. It also assumes that you have an array containing all of the relevant key value pairs.
var customerDeetsArray =[{CustomerID: 400}, {CustomerName: "John"}];
for (var i in customerDeetsArray) {
requestData.data = $.extend(requestData.data, customerDeetsArray[i]);
}
See working example which makes use of console.debug:
http://jsfiddle.net/4Rh72/6/