Create bar chart using mysql data - javascript

I want create bar using mysql data which is returned in JSON Format.
[
{
"Score": "84",
"Trainer": "Jamshaid",
"Subject Name": "Java"
},
{
"Score": "50",
"Trainer": "Zaid",
"Subject Name": "Android"
},
{
"Score": "40",
"Trainer": "Sajjad",
"Subject Name": "iOS"
},
{
"Score": "50",
"Trainer": "Jamshaid",
"Subject Name": "iOS"
}
]
I want to create like this chart
But problem is that this gets formatted from Table. But I have data in JSON as shown above.
Here is the link I am following. Can we convert the JSON Data in a Format so that it can populate chart based on the Data as shown
https://blueflame-software.com/bar-chart-with-data-from-mysql-using-highcharts/

You can process the JSON in the Javascript to build the data required for the chart as shown below:
var jsonFromServer = [
{
"Score": "84",
"Trainer": "Jamshaid",
"Subject Name": "Java"
},
{
"Score": "50",
"Trainer": "Zaid",
"Subject Name": "Android"
},
{
"Score": "40",
"Trainer": "Sajjad",
"Subject Name": "iOS"
},
{
"Score": "50",
"Trainer": "Jamshaid",
"Subject Name": "iOS"
}
];
The above is data from server captured in a variable
The below code helps you to extract the Y axis Values (i.e the unique subject names) from the JSON response:
function getSubjects(){
var subjectsMap = {};
$.each(jsonFromServer, function(index, value){
if(!subjectsMap[value['Subject Name']]){
subjectsMap[value['Subject Name']] = 1;
}
});
return $.map(subjectsMap, function(index, val){ return val; });
}
Then we need to extract the Scores for each trainer in different subject which should be of form: [{name: "Trainer", data: []}] where data is an array of scores in subject whose order should be same as the order of subjects appearing in the Y axis data. Which can be achieved using the below code:
function getTrainers(){
var trainersMap = {};
$.each(jsonFromServer, function(index, value){
if(!trainersMap[value['Trainer']]){
trainersMap[value['Trainer']] = 1;
}
});
return $.map(trainersMap, function(index, val){ return val; });
}
function getMarks(){
var subjects = getSubjects();
var trainers= getTrainers();
var marks = {};
//initialize the trainers scores in all subjects to 0
$.each(trainers, function(index, trainer){
if ( !marks[trainer]){
marks[trainer] = {};
}
$.each(subjects, function(idx2, sub){
marks[trainer][sub] = 0;
});
});
//now populate with the actual values obtained from server
$.each(subjects, function(idx2, sub){
$.each(jsonFromServer, function(index, value){
var trainer = value['Trainer'];
var subName = value['Subject Name'];
var score = value['Score'];
if ( sub == subName){
marks[trainer][sub] = score;
}
});
});
//now format the marks object into the format required for highcharts
//i.e an array of object with properties [{name: "", data:[]}]
return $.map(marks, function(val, index){
var scoreArray = [];
$.each(val, function(index, score){
scoreArray.push(parseInt(score));
});
return {"name": index, "data": scoreArray};
});
}
The working code can be found in the fiddle here.

Related

Access nested members in JSON

I'm trying to access members in a json, however I am running into some trouble. Here is an example of one of the json objects, stored in var obj:
var fs = require('fs');
var obj = [
{
"_id": "52d7f816f96d7f6f31fbb680",
"regNum": "0361300035313000002",
"sd": "2013-01-01T00:00:00",
"pd": "2013-01-25T09:30:29Z",
"prd": "2012-12-18",
"p": 1395000000,
"pt": [
{
"name": name here",
"price": 1395000000,
"OKDP": {
"code": "5520109",
"name": "name here"
},
"sid": "25484812",
"sum": "1395000000",
"OKEI": {
"code": "796",
"name": "name two"
},
"quantity": "1"
}
],
"b": 0,
"c": 0,
"s": 0
}
];
I'm trying to access the sid and sum values, by doing the following:
var sid = [];
var sum = [];
obj.forEach(block => {
var sidOut = block.pt.sid;
var sumOut = block.pt.sum;
sid.push(sidOut);
sum.push(sumOut);
});
console.log(sid);
console.log(sum);
I tried the solution here, however, when I run these it gives me [ undefined ] errors.
Why am I unable to access this two values?
if you see your pt is an array of an object [{}] so you need to select which element you want to access so
var sidOut = block.pt[0].sid;
var sumOut = block.pt[0].sum;
should get you the right result

How to loop json array to get key and value in javascript?

I have below json array structure.. How can i get the key and value of each of the records json object?
{
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}
My expected output is to get the key and value... below as example:
<b>key</b> : cf_1, <b>value</b> : Clinic San
I have tried to loop in the records, but since i don't know the key, so i unable to get the value..
for (var z in records)
{
var value = records[z].cf_1;
alert(value);
}
//i don't know the key here.. i want to get the key and value
The full JSON structure is as below:
{
"forms": [{
"id": 1,
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}, {
"id": 7,
"records": [{
"cf_31": "27/3/2016",
"cf_32": "Singapore",
"cf_33": "dfd555",
"cfe_34": ""
}]
}, {
"id": 11,
"records": [{
"cfsub_10": "9",
"cf_9": "25/3/2016",
"cf_10": "256.50",
"cfe_11": "dfg44"
}]
}]
}
Hope this one is helpful for you.
$.each(value.forms, function(index,array){
$.each(array.records, function(ind,items){
$.each(items, function(indo,itemso){
alert( "Key -> "+indo + " : values -> " + itemso );
});
});
});
var getKeys = function (arr) {
var key, keys = [];
for (i = 0; i < arr.length; i++) {
for (key in arr[i]) {
if (arr[i].hasOwnProperty(key)) {
keys.push(key);
}
}
}
return keys;
};

Is this valid json data?

The url has following json data:
[{ "topic": "cricket",
"value": "Player [ playerid=123, category=b, high=150, total=2300]",
"place": "xyz"},
{ "topic": "cricket",
"value": "Player [ playerid=456, category=c, high=60, total=300]",
"place": "abc"},
{ "topic": "cricket",
"value": "Player [ playerid=789, category=a, high=178, total=5300]",
"place": "bnm"}]
I tried online to check whether this is valid json or not through following link: http://jsonformatter.curiousconcept.com/ it says valid. if it is, how do I access each playerid ?
It is valid JSON, but the data about the player is embedded in a random string. You can do one of two things:
Update the service to send back a different, valid JS value, for example:
"value": {
"type": "Player",
"playerid": 123,
"category": "b",
"high": 150,
"total": 2300
}
Parse the data in the value key yourself:
// Simple regex, not really "parsing"
var playerIdRE = /playerid=(\d+)/i;
var result = playerIdRE.exec(yourData[0].value);
// result[0] is the full match, while result[1] is the ID.
// Or the more complicated version that does full parsing
var format = /\s*(.*?)\s*\[\s*([^\]]+)\s*\]\s*/gi,
keyValuePair = /(\w+)=([^,\]]*),?\s*/gi
function parseComplexDataType(input) {
var result = format.exec(input),
typeName = result[1],
keyValues = result[2],
returnValue = {};
if (!typeName) return returnValue;
returnValue.typeName = typeName;
input.replace(keyValuePair, function(_, key, value) {
returnValue[key] = value;
});
return returnValue;
}
// Usage:
> parseComplexDataType("Player [ playerid=123, category=b, high=150, total=2300]")
Object {typeName: "Player", playerid: "123", category: "b", high: "150", total: "2300"}
For your purposes, it is not valid. Once the JSON is corrected, you simply need to loop through the array and read each value.
var jArray = [{
"topic": "cricket",
"value": {
"type": "Player",
"playerid": 123,
"category": "b",
"high": 150,
"total": 2300
},
"place": "xyz"
}, {
...
}]
To access the JSON data ...
for (var i=0,len=jArray.length; i<len; i++) {
console.log(jArray[i].topic, jArray[i].value.type);
}
Yes, it is. I check it via: http://jsonlint.com/
Extracting "playerid":
Initialise the string to JSONArray.
Iterate over each element in the above array.
Now, from each element extract "value".
Finally, from this string you can get "playerid" by using string methods (see the code below).
Below is the code in Java:
ArrayList<String> player_ids = new ArrayList<String>();
String s = "YOUR STRING";
JSONArray ja = new JSONArray(s);
for(int i =0; i<ja.length(); i++)
{
String value = ja.getJSONObject(i).getString("value");
int start = value.indexOf("=");
int end = value.indexOf(",");
String player_id = value.substring(start+1, end);
player_ids.add(player_id);
}
Hope it helps!!

Take Distinct values to populate Drop down

{ "Result": { "tags": [ { "name": "ABC", "email": "abc1#example.com", "sms": 123 }, {
"name": "ABC", "email": "abc2#example.com", "sms": 456 }, { "name": "ABC", "email":
"abc3#example.com", "sms": 789 }, { "name": "XYZ", "email": "xyz1#example.com", "sms": 976
}, { "name": "ABC", "email": "xyz2#example.com", "sms": 543 } ] } }
I have a JSON data like this. I want to Parse this JSON in PHP or Javascript to populate them in three drop downs.
Name | Email | SMS
But I need to Populate the distinct names in the dropdowns and populate email and sms based on selecting the name.
So far I just created the dropdowns.
Fiddle Link : http://jsfiddle.net/CAB2z/
Example:
Name should have : ABC | XYZ only once (Distinct : Should not repeat the same value).
When we select ABC, the three emails and phone numbers for "ABC" from the JSON should be populated in the second and third dropdown.
Try this,
$(function(){
var json = {
"Result": {
"tags": [{"name": "ABC","email": "abc1#example.com","sms": 123},
{"name": "ABC","email": "abc2#example.com","sms": 456},
{"name": "ABC","email":"abc3#example.com","sms": 789},
{"name": "XYZ","email": "xyz1#example.com","sms": 976},
{"name": "XYZ","email": "xyz2#example.com","sms": 543}]
}
};
var name = [],obj = {};
$(json.Result.tags).each(function (k, v) {
name[k] = (v.name);
obj[k] = {name: v.name,email: v.email,sms: v.sms};
});
$($.unique(name)).each(function (i, v) {
$('#name').append('<option value="'+v+'">'+v+'</option>');
});
$('#name').on('change', function () {
var $that = $(this);
$('#email').html('');$('#sms').html('');
$.each(obj,function (i, v) {
if( $that.val() == v.name) {
$('#email').append('<option value="'+v.email+'">'+v.email+'</option>');
$('#sms').append('<option value="'+v.sms+'">'+v.sms+'</option>');
}
});
}).change();
});
Live Demo
It will returns all results you want. Just append the vaues in
dropdown its your part.
var resultArray = r.Result.tags;
var unique = {};
var distinctName = [];
var email = [];
var sms = [];
for( var i in resultArray ){
if( typeof(unique[resultArray[i].name]) == "undefined"){
distinctName.push(resultArray[i].name); // push the unique names into the array
}
unique[resultArray[i].name] = 0;
email.push(resultArray[i].email); // push the email into the array
sms.push(resultArray[i].sms) // push the sms into the array
}
console.log(distinctName);
console.log(email);
console.log(sms);
In JavaScript, with jQuery, you can do:
var names, emails, smses;
(function() {
data = JSON.parse(data); // Get the data formatted.
var result = {
name: {},
email: {},
sms: {}
};
$.each(data.Result.tags, function(index, value) {
result.name [value.name] = true; // True won't be used, it can be any value.
result.email[value.email] = true;
result.sms [value.sms] = true
});
names = Object.keys(result.name);
emails = Object.keys(result.email);
smses = Object.keys(result.sms);
} ()); // Temporary variables (like result) are destroyed.
// names, emails and smses contain your data.

How to transform JavaScript hashmap?

i'm trying to create a <String, Array()> map from a json object.
Imagine i got this json structure:
[
{
"userId": "123123",
"password": "fafafa",
"age": "21"
},
{
"userId": "321321",
"password": "nana123",
"age": "34"
}
]
The map i want to create would be:
key (string), value (array)
{
"userId": [
"123123",
"321321"
],
"password": [
"fafafa",
"nana123"
],
"age": [
"21",
"34"
]
}
Is it possible to do this? :/
Thanks in advance.
Demo
var json = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';
var list = JSON.parse(json);
var output = {};
for(var i=0; i<list.length; i++)
{
for(var key in list[i])
{
if(list[i].hasOwnProperty(key))
{
if(typeof output[key] == 'undefined')
{
output[key] = [];
}
output[key].push(list[i][key]);
}
}
}
document.write(JSON.stringify(output));
Outputs:
{"userId":["123123","321321"],"password":["fafafa","nana123"],"age":["21","34"]}
function mergeAttributes(arr) {
return arr.reduce(function(memo, obj) { // For each object in the input array.
Object.keys(obj).forEach(function(key) { // For each key in the object.
if (!(key in memo)) { memo[key] = []; } // Create an array the first time.
memo[key].push(obj[key]); // Add this property to the reduced object.
});
return memo;
}, {});
}
var json = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';
mergeAttributes(JSON.parse(json));
// {
// "userId": ["123123", "321321"],
// "password": ["fafafa", "nana123"],
// "age": ["21", "34"]
// }
Javascript's JSON.stringify will help you to convert any JSON compliant object model into a JSON string.

Categories

Resources