How do I select elements from json_encode d array? - arrays

I'm using JSON and javascript to retrieve data from a php file which connects to the database. This is how my php code looks like:
while($row = $stmt->fetch_assoc()) {
$data[] = $row;
}
header("Content-type: text/plain");
echo json_encode($data,true);
This is my Javascript:
var displayfeeds = new ajaxObject('ajax/users/display.feeds.php');
displayfeeds.callback = function (responseText,status) {
var feed = JSON.parse(JSON.stringify(responseText));
$("#feeds-feedback").html(feed);
}
displayfeeds.update();
When I run this, it prints out an array like this:
[
{
"userID":"39160902151",
"content":"bar bar bar bar",
"published":"2011-06-07 10:33:35"
},
{
"userID":"5896858666",
"content":"foo foo foo foo foo",
"published":"2011-06-06 22:54:51"
}
]
My question is: How do I then display say "userID" and "content" from this?
I have really struggled. I am new in JSON.

You need to transform your json objects into html to display them. So in your callback function I would do something like this:
displayfeeds.callback = function (responseText,status) {
var feed = JSON.parse(JSON.stringify(responseText));
var html = '';
// build html for each feed item
for (var i = 0; i < feed.length; i++) {
html += '<h3>UserID:: '+ feed[i]['userID'] +'</h3>';
html += '<p>'+ feed[i]['content'] +'</p>';
html += '<div><strong>published</strong>: '+ feed[i]['userID'] +'</div>';
html += '<hr />';
}
// append content once all html is built
$("#feeds-feedback").append(html);
}

To get first user id:
var feed = JSON.parse(responseText);
feed[0].userID

Related

iterating through json getting empty value

Not able to push values out. Please help!!
function pullJSON(data) {
var url="https://www.eventbriteapi.com/v3/subcategories/?event_status=live&token=XXXXXXXXXXX&page_count=4"; // Paste your JSON URL here
var response = UrlFetchApp.fetch(url); // get feed
var data = JSON.parse(response.getContentText()); //
var dict = JSON.stringify(data);
//Logger.log(dict);
var keys = [];
for(var k in dict) keys.push(k+':'+dict[k]);
Logger.log(keys);
}
Here is the result: [17-03-29 11:41:19:033 EDT] []
JSON data
When you use JSON.stringify(), it will return a string. It looks like you want to have an object, not a string.
Try using this instead of your for loop:
var keys = Object.keys(data).map(function(key){ return key + ':' + data[key]});

Angular parse response from database

I have response from database:
{"status":"success","message":"Data selected from database","data":[{"id":1171,"sku":0,"word_one":"one word","description":"","word_two":"two word","mrp":0,"lang_one":"en","image":"","lang_two":"en","status":"Active","category":"[{\"text\":\"someone\"},{\"text\":\"sometwo\"}]","UserID":188},
...
{"id":1170,"sku":0,"word_one":"something","description":"","word_two":"some two","mrp":0,"lang_one":"en","image":"","lang_two":"en","status":"Active","category":"[{\"text\":\"ever\"},{\"text\":\"never\"}]","UserID":188}]}
Before I make post: angular.toJson($scope.category);
How I can show category something like this
{{category}} = someone, sometwo ?
Because actually I have string :
[{"text":"someone"},{"text":"sometwo"}]
[{"text":"ever"},{"text":"never"}]
...
You can use the below parsing to achieve what you want. Suppose json is the variable received from database.
var json = {"status":"success","message":"Data selected from database","data":[{"id":1171,"sku":0,"word_one":"one word","description":"","word_two":"two word","mrp":0,"lang_one":"en","image":"","lang_two":"en","status":"Active","category":"[{\"text\":\"someone\"},{\"text\":\"sometwo\"}]","UserID":188}]};
var data = json.data[0].category;
var jsonArray = JSON.parse(data);
var category = "";
jsonArray.map(function(obj, i ) {
if(i != 0) {
category += ",";
}
category += obj.text;
});
console.log(category)
At the end , You attach category to $scope.category.
This work:
var parsed = JSON.parse($scope.c.category);
var arr = [];
for(var x in parsed){
arr.push(parsed[x]);
}
$scope.c.category = arr;

How do I use async in node.js

I have created a code in node.js, which use mongoDB. Everything is working fine, but when I use nested loop, it break and don't return the proper values.
DB1.find({},function(error,fetchAllDB1) {
var mainArray = new Array();
for (var i in fetchAllDB1) {
if(fetchAllDB1[i].name) {
var array1 = new Array();
var array2 = new Array();
array1['name'] = fetchAllDB1[i].name;
array1['logo'] = fetchAllDB1[i].logo;
array1['desc'] = fetchAllDB1[i].desc;
DB2.find({is_featured:'1', brand_id: fetchAllDB1[i]._id}, function(error,fetchDB2) {
for (var p in fetchDB2) {
var pArr=[];
pArr['_id'] = fetchDB2[p]._id;
pArr['name'] = fetchDB2[p].name;
pArr['sku'] = fetchDB2[p].sku;
pArr['description'] = fetchDB2[p].description;
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
console.log(pArr);
console.log('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');
array2[p]=pArr;
}
array1['pp']= array2;
});
mainArray[i]=array1;
}
}
console.log('######### LAST #########');
console.log(mainArray);
console.log('######### LAST #########');
});
In my console message its showing
console.log('######### LAST #########');
All Values
console.log('######### LAST #########');
After that
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
All Values;
console.log('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');
I want to use async in my code, so that all data fetching occur as below:
mainarray =
[
[array1] = All Values
[array2] = [0]
[1]
]
mainarray =
[
[array1] = All Values
[array2] = [0]
[1]
]
Your code is very confusing and overly complicated.
What you should do is (psuedo code):
DB1.find(foo) // returns one result
.then(getFromDB2);
function getFromDB2 (res){
return DB2.find(res); // make a query here with mongo drivers `$in`
}
Mongodb : $in operator vs lot of single queries

How to split and parse particular value of json array using Angularjs?

How can i split and parse particular json data using angularjs.
My json is
[{"id":"1", "stud":" name=Alex, roll_no=12 | class=12,sec=1" , "tech":"Sam"},
{"id":"2", "stud":" name=john, roll_no=13 | class=12,sec=2" , "tech":"Sandy"},
{"id":"3", "stud":" name=Cate, roll_no=14 | class=12,sec=1" , "tech":"Sandy"},
]
I want to parse this json formated data like if ID =1 .
Name= Alex.
Roll No=12.
Class=12.
Section=1.
Teacher=Sam.
Iterate through the collection with reduce.
On every Object in the collection parse the stud attribute with Regular Expressions. Create the new string and add it to the new collection.
// Pseudocode
collection.reduce((memo, item) => {
const values = item.stud.match(" name=Alex, roll_no=12 | class=12,sec=1".match(/^ name=(\w*), roll_no=(\d{2}).../))
// Add it to memo in a format you like
return memo
})
I wrote you some functions...
function getRowFromJson(json, id){
for(var i=0; i<json.length; i++)
if('undefined' == json[i].id) continue;
else if(json[i].id==id) return json[i];
return false;
}
function parseStudFromRow(row){
var stud = {};
var chunks = row.stud.split("|");
for(var i=0; i<chunks.length; i++){
var morechunks = chunks[i].split(",");
for(var n=0; n<morechunks.length; n++){
var chunkage = morechunks[n].split("=");
stud[chunkage[0].trim()] = chunkage[1].trim();
}
}
return stud;
}
You use it like this..
var row = getRowFromJson(json, 1);
var stud = parseStudFromRow(row);
console.log(stud);
Check out the example.. https://jsfiddle.net/o0v6nyzu/2/

ui-grid using external Pagination and exporting data

I am currently using ui-grid implemented with external pagination to display my data. I've run into as issue where I can only export the currently viewed data, however I need to be able to export ALL data as well.
Anyone know a work around to export all data using external pagination?
I ended up using csvExport function included with ui-grid. I added an "Export All" custom menu item and it works great! Here is my code:
gridMenuCustomItems: [
{
title: 'Export All',
action: function ($event) {
$http.get(url).success(function(data) {
$scope.gridOptions.totalItems = data.totalFeatures;
$scope.gridOptions.data = data.features;
$timeout(function()
{
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport( uiGridExporterConstants.ALL, uiGridExporterConstants.ALL, myElement );
}, 1000);
});
}
}
]
Hope this helps someone!
Ok, so I took ui-grids server side example and modified their plnkr a bit. I simply created a button outside the ui-grid and that button calls your datasource which converts json into CSV and downloads the file
http://plnkr.co/edit/xK3TYtKANuci0kUgGacQ?p=preview
<button ng-click="exportAllData()">Export Data</button>
then in your controller:
$scope.exportAllData = function()
{
setTimeout(function()
{
$http.get('largeLoad.json').success(function(response)
{
$scope.JSONToCSVConvertor(response, "Data Title", true);
});
},100);
};
$scope.JSONToCSVConvertor = function(JSONData, ReportTitle, ShowLabel)
{
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//Set Report title in first row or line
CSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = "MyReport_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g,"_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
JSONToCSVConverter() source: http://jsfiddle.net/hybrid13i/JXrwM/

Resources