Json and lawnchair usage - json

i saw below example in lawnchair documentation,
var store = new lawnchair({name:'testing'}, function(store) {
// create an object
var me = {key:'brian'};
// save it
store.save(me);
// access it later... yes even after a page refresh!
store.get('brian', function(me) {
console.log(me);
});
});
i am not sure i understood it correctly or not, but based on my understanding, i wrote code like this, (name,dtime,address are variables with value)
db = Lawnchair({
name : 'db'
}, function(store) {
console.log('storage open');
var formDetails = {
"candidateName" : name,
"DateTimeOfVerification" : dtime,
"ResidentialAddress" : address
}
store.save({key:"fdetails",value:formDetails});
store.get("fdetails", function(obj) {
alert(obj);
});
});
but, in alert i did not got value, i got "[object Object]".
1) how to store multi-attribute json object in lawnchair
2) how to get that json object.

Try this:
db = Lawnchair({name : 'db'}, function(store) {
console.log('storage open');
var formDetails = {
"candidateName" : "Viswa",
"DateTimeOfVerification" : "30/07/2012",
"ResidentialAddress" : "3 The Road, Etcc...."
}
store.save({key:"fdetails", value:formDetails});
store.get("fdetails", function(obj) {
console.log(obj);
alert(obj.value.candidateName);
alert(obj.value.DateTimeOfVerification);
alert(obj.value.ResidentialAddress)
});
});
1) You are storing the formDetails structure correctly.
2) obj.value is the collection you are looking for
Had you added the console.log(obj); line into your code and then inspected the console you could probably have worked this out for yourself.

Related

Postman Object hasOwnProperty Tests

I am trying to evaluate a JSON, so that I can know if the properties are correct, I have the following code:
var data = JSON.parse(responseBody);
Object.keys(data).forEach(key => {
if(data.hasOwnProperty(key)){
console.log("Have all properties");
}
});
The problem I have is that, the answer is shown to me "n" times, how can I make it show it to me only once after evaluating that the properties exist?
This should do it:
var data = JSON.parse(responseBody);
let hasProperties = true;
Object.keys(data).forEach(key => {
if!(data.hasOwnProperty(key)){
hasProperties = false;
}
});
if (hasProperties) {
console.log("Have all properties");
}

How do I access the information inside the response body of a postman test Get call

Below is a JSON format from the response body
{
"properties":{
"name":"Jake",
"id":123,
"HashData":[
{
"Major":"CS",
"code":234
}
]
}
}
I tried using:
var x = pm.response.json().properties;
console.log(x.HashData); // it returned HashData is [object object]
console.log(x.HashData.code); // it returned undefined
How else can I see or access the data?
And how do you use this in patch as in if you want to change code from 234 to 567?
You need to use the pm object.
Try console.log(x.HashData[0].code);
Your HasData is an array;
pm.test (
"Response HashData has a code.",
function()
{
var data = pm.response.json();
pm.expect(data.properties.HashData[0]).to.have.property('code');
}
);
This if for object but for arrays you need to use the key.
pm.test (
"Response has name property.",
function()
{
var data = pm.response.json();
pm.expect(data.properties).to.have.property('name');
}
);
More test documentation here : https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference/
To change the value you would do something like :
data.properties.HashData[0].code = 567

How to i display file from JSON object which contains an array?

Below is my json object which is returned. As you can see i have an array called "DocumentVersions" with a blob address of the file that i want to display. On the success function i want to display the image under a div. I tried looping through but i don't know how to display the image. I could have multiple files returned.
{
"FileUploadID":"27",
"DocumentVersions":[
{
"Active":true,
"DocumentVersionID":"5",
"FileName":"Logo0112.png",
"ContentLength":18846,
"ContentType":"image/png", "
"RevisionNumber":0,
"RevisionDate":"2017-08-01T12:24:04.7748026+01:00",
"Blob":"https://address/documents/75755df4af5f.png",
"BlobFileName":75755df4af5f.png"
}
],
"success":true,
"id":"27",
"message":"The Files have been uploaded"
}
Here is my success function. Where i get a 'Cannot read property 'Blob' of undefined'
myDiv.on("complete", function (data) {
res = JSON.parse(data.xhr.responseText);
console.log(res);
if (res.success == true) {
for (var key in res) {
var optionhtml = '<p="' + res[key].FileUploadID +
'">' + res[key].DocumentVersions.Blob + '</p>';
$(".test").append(optionhtml);
}
}
else {
alert(res.message);
}
});
As you can see, the DocumentVersions is not a object, it's a array with objects (only one object in this case).
{
"FileUploadID":"27",
"DocumentVersions":[
{
"Active":true,
"DocumentVersionID":"5",
"FileName":"Logo0112.png",
"ContentLength":18846,
"ContentType":"image/png", "
"RevisionNumber":0,
"RevisionDate":"2017-08-01T12:24:04.7748026+01:00",
"Blob":"https://address/documents/75755df4af5f.png",
"BlobFileName":75755df4af5f.png"
}
],
"success":true,
"id":"27",
"message":"The Files have been uploaded"
}
You need to specify the inner object in the array that you want to get data:
res[key].DocumentVersions[0].Blob
Thanks for your help, I solved my problem by using the following code this lets me get the image files and display.
res.DocumentVersions.forEach(function (obj) {
var img = new Image();
img.src = obj.Blob;
img.name = obj.FileName;
img.setAttribute("class", "fileLoad");
$("#fileupload").append(img);
});

How to convert a MongoDB document to JSON Object

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()))
}

angularjs localstorage displaying data

i been tryi'n to use angular nowadays. i'm just hoping if someone could help me why i cant fetch localstorage data like the below codes. thanks
[
{
"name": "firstname",
"email": "email#yahoo.com"
}
]
service.js
getItem: function (item) {
var temp = localStorage.getItem(item);
if (!temp){
return [];
}
return JSON.Parse(temp);
}
controller.js
profile.push({
name: 'firstname',
email: 'rmail#yahoo.com'
});
localStorage.setItem('profiles', JSON.stringify(profile));
console.log(service.getItem('name') + ' : this should output the name');
console.log(service.getItem('email') + ' : this should output the email');
Can you please try this
var array = service.getItem('profiles');
for(var i=0;i<array.length;i++){
console.log(array[i].name, array[i].email)
}
To forego using parsing and deal with any of this you can try a factory I recently created, it let's you store and retrieve arrays and objects. Also it let's you bind to $scope.variables:
https://github.com/agrublev/Angular-localStorage