Json response + Node.js - json

In my node app i pass bunch of queries as Object.I have to form as exact format of request.
Consider my request as:
{q0:{query0},q1:{query1},q2:{query1}}
My reponse should be {q0:{response0},q1{response1},q2{response2}
My actual query(In my app):
{"q0":{"query":"James Madison","type":"/people/presidents","type_strict":"should"},
"q1":{"query":"George Washington","type":"/people/presidents","type_strict":"should"},
"q2":{"query":"John Adams","type":"/people/presidents","type_strict":"should"},
"q3":{"query":"James Monroe","type":"/people/presidents","type_strict":"should"},
"q4":{"query":"Thomas Jefferson","type":"/people/presidents","type_strict":"should"}}
But my response is coming as:
{"result":[q0result,q1result,q3result]}
My code:
for (var id in presidents ) {
var match
if (query == presidents[id]) {
//console.log(" Inside match")
match = true;
}
else {
match = false;
}
matches.push({
"id": id,
//"name": name,
"score": 100,
"match": match,
"type": [{
"id": "/people/presidents",
"name": "US President"
}]
})
}
callback(matches);
json = JSON.stringify({"result":matches});
res.writeHead(200, {'content-type':'application/json'});
res.end(json);
Please help me to solve this..Thanks in advance.

You are pushing the result in an array instead you should create a property in the result object as below
var matches = {};
for (var id in presidents ) {
if (query == presidents[id]) {
//console.log(" Inside match")
match = true;
}
else {
match = false;
}
matches[id] ={
"id": id,
//"name": name,
"score": 100,
"match": match,
"type": [{
"id": "/people/presidents",
"name": "US President"
}]
};
}
callback(matches);

Related

How to get total no of count of a field in a Json Array using TypeScript

I have a Json array.
"user": {
"value": [
{
"customerNo": "1234"
},
{
"customerNo": "abcd"
},
{
"customerNo": "1234"
}
]
}
Here I want to get the count of total number of customer. I am getting it like this:
json.user.value.length;
And the output is 3. But the thing is I have to avoid duplicate customer number.
As here "1234" is there 2 times. So my output should be 2
How to do this using Typescript.
Use lodash:
var uniqueCustomer = _.uniqBy(json.user.value, 'customerNo');
var length = uniqueCustomer.length
Here is link which shows How to use lodash in your app.
You can use Array.reduce to count the unique customers.
const data = {
"user": {
"value": [
{
"customerNo": "1234"
},
{
"customerNo": "abcd"
},
{
"customerNo": "1234"
}
]
}
};
function getCustomerCount(arr) {
let tmp = [];
return arr.reduce((acc, curr) => {
if(!tmp.includes(curr.customerNo)) {
return tmp.push(curr.customerNo);
}
return acc;
}, 0);
}
let customers = data.user.value;
let customerCount = getCustomerCount(customers);
console.log(customerCount);

JSON value search

I'm getting below JSON result from a PHP page using ajax request. I tried a lot to get the desired result. I have done below approach but still unable to get as expected.
{
"search": {
"entry": [
{
"attribute": [
{
"name": "title",
"value": [
"Mr."
]
},
{
"name": "mail",
"value": [
"kiran#gmail.com",
"Kiran#yahoo.com",
"kiran#hotmail.com"
]
}
]
}
]
}
}
I have tried the following search to get the value using Defiant.js
success: function (data) {
var xx=JSON.stringify(data);
// var got = $.each(data.search.entry[0].attribute, function (i, v) {
// return v;
//
// });
alert(xx);
var z=JSON.search( xx, '//*[name="title"]/value[1]' );
alert(z);
},
How would I can get results like title='Mr' or mail='kiran#gmail.com'.
Why you need regex solution if your json has proper structure. I have seen your code and json and it seems that you need first index value for title and mail. see following function which can search both title and mail.
var arrt = ' {"search": {"entry": [ {"attribute": [ {"name": "title","value": [ "Mr."] }, {"name": "mail","value": [ "kiran#gmail.com", "Kiran#yahoo.com", "kiran#hotmail.com"] }] }] }}';
SearchMyWordTT(arrt,"title");
//SearchMyWordTT(arrt,"mail");
function SearchMyWordTT(arr,index){
arr = JSON.parse(arr);
for(var i=0;i< arr["search"]["entry"][0]['attribute'].length;i++){
if(typeof (arr["search"]["entry"][0]['attribute'][i]['name']) !="undefined" && arr["search"]["entry"][0]['attribute'][i]['name'] == index)
retIn = arr["search"]["entry"][0]['attribute'][i]['value'][0];
}
return retIn;
}

How to POST Geolocation values to a Sharepoint List Field with Rest API?

I need to post two values Caption and Location, later being a GeoLocation field in Sharepoint list. I am using the following JSON:
{"__metadata": { "type": "SP.ListItem" }, "Caption": "Testing", "Location": "POINT (78.4 17.4)"}
But it's not working. Shows the following error:
Cannot deserialize data for type Microsoft.SharePoint.SPFieldGeolocationValue
I am doing this from Xcode.
SharePoint REST service expects SP.FieldGeolocationValue to be specified in the following format:
{
"__metadata": {
"type": "SP.FieldGeolocationValue"
},
"Altitude": <val>,
"Latitude": <val>,
"Longitude": <val>,
"Measure": <val>
}
JavaScript example
The example demonstrates how to create list item in Contacts list and set Geolocation value for Location field:
function createContact(name,location){
var listTitle = 'Contacts';
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/items";
var payload = {
"__metadata": { "type": "SP.ListItem" },
"Title": name,
"Location": {
"__metadata": {"type": "SP.FieldGeolocationValue"},
"Latitude": location[0],
"Longitude": location[1],
}
};
return executeJson(url,'POST',null,payload);
}
createContact("Work Address", [60.2872339,24.8516785])
.done(function(data)
{
console.log('Contact has been created');
})
.fail(function(error){
console.log('An error occured while creating contact');
});
where
function executeJson(url,method,headers,payload)
{
method = method || 'GET';
headers = headers || {};
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if (typeof payload != 'undefined') {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}

Access nested JSON object in AngularJS controller

I am new to AngularJS and trying to create a $scope for tracks for later usage
data.json (sample):
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
Controller
app.controller('lyricsCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(result) {
$scope.albums = result.data;
$scope.tracks = result.data.tracks;
console.log($scope.tracks); //Undefined...
});
});
Why is $scope.tracks undefined?
If your json file is as is:
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
We have a response of:
data: Array[1]
0: Object
album: "Album name"
tracks: Array[2]
Since data is returned as an array you would handle like any other javascript array and access by index, so you could do a loop or if you know only 1 result is going to be returned you could use the zero index:
$http.get('data.json').then(function(result) {
console.log(result);
// Assign variables
$scope.album = result.data[0].album;
$scope.tracks = result.data[0].tracks;
for (var i = 0, l = $scope.tracks.length; i < l; i++) {
console.log($scope.tracks[i].title);
}
});
result.data is an array,So you must have to use index to access its child like:-
$scope.tracks = result.data[0].tracks;
It should be result.data[0].tracks as data is an array
$scope.tracks = result.data[0].tracks;

POST unconventional JSON with emberjs

I'm trying to post JSON to an api through the ember framework, but my api JSON doesnt follow ember conventions. This is what I am trying to post:
[
{
"id": 1,
"name": "Mary Kelly",
"email": "mk#gmail.com",
"subjects": ["1","2"]
}
]
Ember expects this:
{
"user": {
"id": 1
"name": "Mary Kelly",
"subjects": ["1", "2"],
},
"subjects": [{
"id": "1",
"name": "History"
}, {
"id": "2",
"name": "Maths"
}]
}
So, I need a custom serializer in order to make the post, and to do all other CRUD operations. This is what I have:
App.UserSerializer = DS.RESTSerializer.extend({
extractSingle: function(store, type, payload, id, requestType) {
var subjects = payload.subjects,
subjectIds = subjects.mapProperty('id');
var p = {};
p.user = payload;
p.user.subjects = subjectIds;
p.subjects = subjects;
console.log('extractSingle', JSON.stringify(p));
return this._super(store, type, p, id, requestType);
},
extractArray: function(store, type, payload, id, requestType) {
var p = { users: [], subjects: [] };
for (var i = 0; i < payload.length; i++) {
var user = payload[i];
var subjects = user.subjects,
subjectIds = subjects.mapProperty('id');
for (var j = 0; j < subjects.length; j++) {
p.subjects.push(subjects[j]);
}
user.subjects = subjectIds;
p.users.push(user);
}
return this._super(store, type, p, id, requestType);
}
serializeIntoHash: function(hash, type, record, options) {
Ember.merge(hash, this.serialize(record, options));
}
});
extractSingle and extractArray work fine for get requests, but the serializeIntoHash function for posting isn't working for me- can anyone help?
I'm showing it as working, per the serialize hash you've implemented, extraxt* only run on get requests, serializeIntoHash is used for PUT/POST
http://emberjs.jsbin.com/OxIDiVU/58/edit