Retrieve data without _id and _ref from coucgdb - json

I have a database with lots of document and i am using field type to define it as a table. I want to populate angularjs ui-grid with the JSON data coming in value. So i have created a view:
function(doc) {
if(doc.type === 'userTable'){
emit(doc._id, {userName:doc.userName,fName:doc.fName});
}
}
When i hit the url http://127.0.0.1:5984/rpt_db/_design/Dsgn_userjson/_view/Vw_userjson/ it gives me :
{"total_rows":1,"offset":0,"rows":[
{"id":"f43a147cd5c961fcfe4e1da1b800013a",
"key":"f43a147cd5c961fcfe4e1da1b800013a",
"value":{"userName":"rp670249","fName":"Ranjeeth"}}
]}
Now in my client code i need to do a loop and make data as JSON.
result.rows.forEach(function(item) {
var temp = { "id": item.value.userName, usrName: item.value.fName};
console.log(temp);
//Update data of grid using temp variable.
});
Is there an easy way so that i can directly use what's coming as part of couchdb JSON output which can be used as is in angular ui-grid.

You can refer column values using json dot notation in the columnDefs. Since your actual values are inside "value". you can create column definition like this,
$scope.myData = {"total_rows":1,"offset":0,"rows":[
{"id":"f43a147cd5c961fcfe4e1da1b800013a",
"key":"f43a147cd5c961fcfe4e1da1b800013a",
"value":{"userName":"rp670249","fName":"Ranjeeth"}}
]}
$scope.gridOptions = {
data : $scope.myData.rows,
columnDefs : [
{name:"id",field:"value.userName"},
{name:"usrName",field:"value.fName"}
]
};
Here's a working plnkr.
http://plnkr.co/edit/juLZeT6I0LOlek4QnMSP?p=preview

Related

cloudant view for nested json documents

I am trying to create a view in Cloudant DB which will pick up all the JSON documents based on the value of one field (SAVE_TYPE_SUBMIT). My problem is that, the JSON document contains nested fields. Please take a look at the sample document below.
{
"_id ": "70f79cc9309fd8b2bcca90efd871f993 ",
"_rev": "1-18fe726fc3d99f50a945ab30c9ffeb4b",
"NAME": "qqq",
"EMAIL": "qqq",
"TITLE": "qq",
"DATE_OF_REPORT": "2017/08/17",
"PUBLIC_OFFICIALS_CONTACTED": [{
"NAME_PUBLIC_OFFICIAL": "qq"
},
{
"TITLE_PUBLIC_OFFICIAL": "qq"
}
],
"MANAGER": "qq",
"SAVE_TYPE_SUBMIT": "Submit"
}
The view created is :
function(doc) {
if (("SAVE_TYPE_SUBMIT" in doc) && (doc.SAVE_TYPE_SUBMIT == "Submit")) {
emit (doc.LAST_UPDATE_BY, [doc.NAME, doc.EMAIL, doc.TITLE, doc.DATE_OF_REPORT, doc.PUBLIC_OFFICIALS_CONTACTED, doc.MANAGER]);
}
}
When I try to fetch the data from this view into my application, I do not get the value of the nested fields, i.e. NAME_PUBLIC_OFFICIAL and TITLE_PUBLIC_OFFICIAL. I see those fields as [object,object].
Please note that PUBLIC_OFFICIALS_CONTACTED can contain multiple Name and Title fields.
Please help understand how the view needs to be customized to get the value of the nested fields. I am having a hard time with this and any guidance or material will be highly appreciated!
Create a map function of this form:
function(doc) {
if (("SAVE_TYPE_SUBMIT" in doc) && (doc.SAVE_TYPE_SUBMIT == "Submit")) {
emit(doc.LAST_UPDATE_BY, { name:doc.NAME, email: doc.EMAIL, title: doc.TITLE, date: doc.DATE_OF_REPORT, officials: doc.PUBLIC_OFFICIALS_CONTACTED, manager: doc.MANAGER});
}
}
This is very similar to your map function except that it emits a value which is an Object instead of an array. This object can represent a subset to the original document.
If you need ALL the fields from the original document, then you could modify the function to:
function(doc) {
if (("SAVE_TYPE_SUBMIT" in doc) && (doc.SAVE_TYPE_SUBMIT == "Submit")) {
emit(doc.LAST_UPDATE_BY, null);
}
}
and add ?include_docs=true when querying the view to add the original document bodies to the response.

Filter JSON data based on current URL route

The problem
I'm trying to filter json data and display only a portion of it on an Angular page, based on the page's current URL.
In detail
I have a list of 100 JSON objects, and each one looks like this:
{
"name": "Evangeline Perreault",
"age_1": 1,
"total_age": 1,
"photo_small": "img/400/001_400.jpg",
"photo_medium": "img/800/001_800.jpg",
"photo_large": "img/1200/001_1200.jpg",
"photo_extralarge": "img/1600/001_1600.jpg",
"video": 67443664,
"id": 1,
"quote": "test quote here and here",
"type": 1
},
The 'type' attribute is what I want to use to filter out the subsets of my data. With that in mind, I tried to setup my URL structure to tie the type attribute here to my url. Here is my route:
angular.module('100_Ages', ['mydirectives', 'ngResponsiveImages']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/100_Ages/nav/:personType', {templateUrl: 'partials/person-list.html', controller: NavListCtrl}).
otherwise({redirectTo: '/100_Ages'});
}]);
So, I have pointed the route to the 'type' field in my JSON and I tried writing a controller to tie the two together.
function NavListCtrl($scope, $routeParams, $http) {
$http.get('person.json').success(function(data) {
angular.forEach(data, function(person) {
if (person.type == $routeParams.personType)
$scope.person = person;
});
});
}
And here is my partial template:
<div class="nav_outer"><img class="nav_img" ng-src="{{person.photo_small}}" ng-alt="{{person.name}}" /></div>
I expected this to display all the matching images for the URL type I'm on. So, if I'm on "/100_Ages/nav/3", I expected all the images (roughly 10 pictures) from the objects with a type of "3" to display. However, it only displayed the last object with a type of "3".
So, I tried an ng-repeat like so:
<div class="nav_outer" ng-repeat="person in persons"><img class="nav_img" ng-src="{{person.photo_small}}" ng-alt="{{person.name}}" /></div>
I expected that to loop through and show all the matching images, but that made nothing at all show up.
I think my problem has to do with the angular.forEach, but I'm not sure how else to tie my JSON type to the page's typeid.
Thanks for any suggestions.
The ng-repeat should work if you push each item into an array. (Also, you are referring to a 'persons' object in the ng-repeat, which doesn't exist according to code provided). So, try this:
$http.get('person.json').success(function(data) {
$scope.persons = [];
angular.forEach(data, function(person) {
if (person.type == $routeParams.personType)
$scope.persons.push(person);
// or alternatively - this.push(person), with the optional 3rd param of $scope.persons (I don't really understand that, but whatever...)
});
});
Now with the array populated, your ng-repeat="person in persons" should work.
UPDATE:
If the success object was already an array of objects, then just set the scope object to the array - no need to iterate through them:
$http.get('person.json').success(function(data) {
$scope.persons = data;
})

Populate Dojo's datagrid with JsonRest and custom json arrays

I have a grid that I am creating drawing off a JSON data source that is formatted like this:
[{"user":{"username":"foo","url":"bar"}},
[{"product":{"name":"banana","price":"85"}},
{"product":{"name":"peach","price":"66"}},
{"product":{"name":"strawberry","price":"78"}}
]
]
But I cannot figure out how to tell datagrid to use the contents of the products to populate the datagrid. Here is my datagrid code:
<script>
require(["dojo/store/JsonRest"], function (JsonRest) {
myStore = new JsonRest({ target: 'myurl', handleAs: 'json'
});
});
require(["dojox/grid/DataGrid", "dojo/data/ObjectStore", "dojo/domReady!"
], function (DataGrid, ObjectStore) {
grid = new DataGrid({
store: dataStore = new ObjectStore({ objectStore: myStore }),
structure: [
{ name: "Procuct", field: "name", width: "200px" }
]
}, "grid3");
grid.startup();
});
</script>
<div id="grid3"></div>
I do not get any error, but I cannot see that the grid gets populated.
It is a similar question to THIS, but the data structure is a bit different.
I think it has something to do with your json structure.
The first part of your jsonArray is an object, the second an array:
[object,ArrayOfProducts]
How should DataGrid find the necessary data if you hide it in an array within an array & then inside the attribute product.
Try passing something simple via json like:
[{"name":"banana","price":"85"},
{"name":"peach","price":"66"},
{"name":"strawberry","price":"78"}]
Have you tried grid.renderArray(dataStore) to populate the grid with the conent ?
An option is to append a new property to the json object prior to dataStore.query() call. This can be accomplished with dojo/aspect. See article for other examples.
aspect.before(dataStore, "query", function(items) {
items.forEach(function(item) {
//Do something here. I'll combine two properties.
item.newProperty = item.propertyValueA + "-" item.propertyValueB;
return item;
});
return items;
});
When dataStore.query() is called, the function above is called above. This results in a new property be added to the json object. In the example above, the newProperty is a concatenation of propertyValueA and propertyValueB.
This may allow you to manipulate the json as needed.

Need help in binding dynamic JSON to Highcharts

I have the JSON data received from the server as:
[{"Text":"TRUCKLOAD","Spend":32323348.4},
{"Text":"NON-SYNDICATED:QUALITATIVE & QUANTITATIVE","Spend":23270306.54},
{"Text":"SAMPLING & EVENTERVICES","Spend":18924795.75},
{"Text":"OTHER LOGISTICS","Spend":18353919.01},
{"Text":"CONSTRUCTION AND INSTALLATION","Spend":13248733.26},
{"Text":"SECURITY SERVICES","Spend":9210534.97},
{"Text":"TAXES","Spend":8661964.99}]
Can anybody help me to bind this data dynamically to a piechart?
Another problem is that the highchart requires me to change the labels as Name and a y tag of JSON instead of the Text and Spend tag in my JSON. How do i change my JSON for that? I have scoured the net for the same but all examples only seem to show the binding of JSON from an external file.
You can see demos' source here and then click view options button.The best way to do it is format your json on your backend before you receive it.
But if you want to do it, you can use the following code:
var json = [{
"name":"TRUCKLOAD",
"y":32323348.4
}, {
"name":"NON-SYNDICATED:QUALITATIVE & QUANTITATIVE",
"y":23270306.54
}, {
"name":"SAMPLING & EVENTERVICES",
"y":18924795.75
}];
var data = [];
for(var i in json) {
var serie = new Array(json[i].name, json[i].y);
data.push(serie);
}
Demo

working with JSON data, trying to parse nested data

I just working with JSON data and am playing around with jQuery and Ajax requests. Pretty basic stuff, but here's my problem.
I have a basic data set which I was using for time tracking. I know how to parse the simple JSON data like this:
{
"end" : "1/18/2011",
"start" : "1/18/2011",
"task" : "Code Review",
},
It's the more complicated stuff I'm trying to parse like this where I'm trying to pull the "time" data out.
{
"end" : "1/17/2011",
"start" : "1/17/2011",
"task" : "Exclusive Brands",
"time" : {
"analysis" : 4,
"documentation" : 3,
"meetings" : 2
}
This is the code for the script I've been using to parse the simple data:
$(function() {
$('.load').click(function(){
$.getJSON("data.js",function(data){
$.each(data.timesheet, function(i,data){
var div_data ="<div class='box'>"+data.start+" "+data.task+"</div>";
$(div_data).appendTo("#time-tracking");
});
}
);
return false;
});
});
My question is what's the format to parse the time data, or what's the best way to parse the information nested inside the time element?
Any help will be greatly appreciated.
A JSON string will be parsed into an object. When parsed, the time is the key of one object. You could retrieve the value of this object through the dot operator (.).
data = JSON.parse('{"end":"1/17/2011", "start":"1/17/2011", "task":"Exclusive Brands", "time": {"analysis":4, "documentation":3, "meetings":2 } }')
// => obj
data.time.analysis
// => 4
In your case similarly you could use the data.time.meetings to access your data from remote server.
Unless I am terribly mistaken, since jquery already converted data into a javascript for you, you should be able to access time as if it was a javascript object like so:
var analysis = data.time.analysis;
var documentation = data.time.documentation;
var meetings = data.time.meetings;
etc...