Convert data from received JSON format to JVectorMap format - javascript

I am developing dashboard of a MIS in MVC 5, and in that dashboard I want to use JVectorMap to load the registered countries. So following is my controller action that returns the JSON
public JsonResult registeredCountries()
{
var ret = db.View_RegisteredCountries.Select(x => new { Key = x.CountryCode, Value = x.TotalCompanies }).ToDictionary(x => x.Key, x => x.Value).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
and following is my JS code to get the JSON
var data = {};
$.ajax({
url: 'registeredCountries',
type: 'GET',
traditional: true,
async: false,
cache: false,
//async: false,
dataType: 'json'
}).done(function(result) {
data = result;
});
But my problem is that JVectorMap use the array in the following format
data_array = {
"US": 4977,
"AU": 4873,
"IN": 3671,
"BR": 2476,
"TR": 1476,
"CN": 146,
"CA": 134,
"BD": 100
};
but the returned JSON is in the following format
[{ "Key": "SA", "Value": 4 }]
How do I convert the above JSON to the following format so that JVectorMap could be populated.
data_array = {
"SA":4
}

Simply a matter of walking the array of inputs and create an object from each entry.
// set up some sample data - in your case you already have this.
var data = JSON.parse('[{"Key":"SA","Value":4},{"Key":"US","Value":12},{"Key":"BR","Value":6}]')
var obj={} // make a new object to build results.
for (var i =0; i < data.length; i = i + 1) {
obj[data[i].Key] = data[i].Value
}
// Note jquery only used for this debug output.
$("#output").html(JSON.stringify(obj))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'></div>

Related

extract an URL from a JSON response of wikipedia api

I need to extract the URL of an image from a JSON response (maybe I could put it in a variable).
I read this page on the MediaWiki API help
I follow this example to get the information about images on a page:
https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100
that return this JSON:
{
"batchcomplete": "",
"query": {
"pages": {
"2061": {
"pageid": 2061,
"ns": 0,
"title": "Albert Einstein",
"thumbnail": {
"source": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Albert_Einstein_Head.jpg/75px-Albert_Einstein_Head.jpg",
"width": 75,
"height": 100
},
"pageimage": "Albert_Einstein_Head.jpg"
}
}
}
In which way can I extract the URL of the image?
I tried this:
$.ajax({
type:"get",
url:"https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json",
dataType:"jsonp",
contentType:"application/json; charset=utf-8",
success: function(data) {
var urlImage = data.query.pages.2061.thumbnail.source;
var stgurl = JSON.stringify(urlImage);
alert(stg);
}
})
but doesn't work.
Yes, it doesn't work because this url: https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100 doesn't return JSON but HTML. If you want the JSON representation, you need to append &format=json to your url.
Change data.query.pages.2061.thumbnail.source to data.query.pages["2061"].thumbnail.source as you can't use numbers in a dot notation.
And also the alert; change stg to stgurl
$.ajax({
type:"get",
url:"https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json",
dataType:"jsonp",
contentType:"application/json; charset=utf-8",
success: function(data) {
var urlImage = data.query.pages["2061"].thumbnail.source;
//var stgurl = JSON.stringify(urlImage); - unnecessary JSON.stringify
var stgurl = urlImage;
alert(stgurl);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I tried to use the solution in this post:
iterating through json object javascript
Use the recursion in this way:
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
it seems to work.

Iterating over JSON Data on AJAX Success Using JQuery

I have an AJAX call that return JSON data from a query:
<script>
function retrieveTrips(){
// Get a history of trips
$.ajax({
url:'cfcs/mileagedata.cfc?method=getTrips&returnformat=json',
data: { ticket_id: #get_ticket.ticket_id# },
success: function(response) {
$("##tripDate").html(response);
console.log(response);
}
});
}
</script>
I would like to iterate over the returned JSON data on the success function and output it to an HTML table using JQUERY. The closest I can come to this is just outputting all the data to a div in my table. Can anyone give me a hand on how that JQUERY code would look?
Here is my JSON response:
{
"COLUMNS": ["ID", "VEHICLE_ID", "TICKET_ID", "_DATE", "START_ODOMETER", "END_ODOMETER", "ORIGIN", "DESTINATION", "TOTAL_MILEAGE", "EXPENSES", "DESCRIPTION"],
"DATA": [
[1650, "6", "30996", "September, 29 2016 00:00:00 -0400", "11782", "11822", "Jaydien", "Mazza", "40", "0.00", ""]
]
}
MY EDITS:
<script>
function retrieveTrips(){
// Get a history of trips
$.ajax({
url:'cfcs/mileagedata.cfc?method=getTrips&returnformat=json',
data: { ticket_id: #get_ticket.ticket_id# },
success: function(response) {
$("##tripDate").html(response);
for (i = 0; i < response.DATA.length; i++) {
var row = response.DATA[i];
console.log(row);
}
}
});
}
</script>
Try this in your success call, place this instead of your console.log();
response = JSON.parse(response);
for (i = 0; i < response.DATA.length; i++) {
var row = response.DATA[i];
console.log(row);
}
Also you have a ## which should be just 1 # or else it wont return to the propper element
The return json is a JSON returned with two properties both containing an Array the first property tell you what the columns mean the second one contains the actual data, to approach only the data you call response.DATA, DATA is the property name in the json object

Get JSON data with AJAX and then modify raphael.js script

This is what I want to achieve:
I want to create an interactive map using raphael.js.
Using Php, I get datas from MySql DB and converted into a JSON file.
So far so good.
Inside my raphael js file, I must now:
get those datas
use them in order to modify my raphael file.
I am currently stuck at this first step.
Here's my simplified JSON file (let's call it countries.json) :
[
{
"id": "1",
"type": "Country",
"title": "France",
"published": "1",
"description": "Republic"
},
{
"id": "2",
"type": "Country",
"title": "Belgium",
"published": "0",
"description": "Monarchy"
}
]
Here comes the simplified raphael.js
var rsr = Raphael('map', '548', '852');
var countries = [];
var france = rsr.path("M ... z");
france.data({'published': '1', 'type': '', 'title': '', 'description':''});
var belgium = rsr.path("M ... z");
belgium.data({'published': '0', 'type': '', 'title': '', 'description':''});
countries.push(france,belgium);
At the end of the raphael js, I make an Ajax request (using jquery) to get my JSON datas :
$.ajax({
type : 'GET',
url : 'system/modules/countries.json',
data: {get_param: 'value'},
dataType : 'json',
success : function(data, statut){
console.log(statut);
},
error : function(data, statut,erreur){
console.log(statut);
},
complete: function (data) {
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
}
});
Here come the troubles:
I get a 'success' status trough the success function.
BUT I got an error while completing the script :
Uncaught SyntaxError: Unexpected token o
What did I miss? Can't figure out what is different from http://jsfiddle.net/fyxZt/4/ (see how to parse json data with jquery / javascript?)
That was just for part 1 :-)
Assuming someone could help me to fix that, I still then have no idea how to write js loop that will set the raphael vars attributes as it:
var rsr = Raphael('map', '548', '852');
var countries = [];
var france = rsr.path("M ... z");
france.data({'published': '1', 'type': 'Country', 'title': 'France', 'description':'Country'});
var belgium = rsr.path("M ... z");
belgium.data({'published': '0', 'type': 'Country', 'title': 'Belgium', 'description':'Monarchy'});
communes.push(france,belgium);
Thanks an advance for your help and please excuse my unperfect english!
Vinny
There is no data argument passed to the complete callback,
according to jQuery API:
complete
Type: Function( jqXHR jqXHR, String textStatus )
(...)The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror").
So you only need to use the success callback :
$.ajax({
type: 'GET',
url: 'system/modules/countries.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function (data, statut) {
var json = data;
$(json)
.each(function (i, val) {
$.each(val, function (k, v) {
console.log(k + " : " + v);
});
});
},
error: function (data, statut, erreur) {
console.log(statut);
}
});
Concerning your second question, you cannot interact directly with variable name (accessing dynamic variable) in js, so you'll need to create an object where values are indexed by one of your json's values. However, the cleanest way to handle this would probably be to add your paths to the json...
var rsr = Raphael('map', '548', '852');
var countries = [];
//here I used the "id" property from the json
var paths={
"1":rsr.path("M ... z"),
"2":rsr.path("M ... z")
};
countries.push(france,belgium);
$.ajax({
type: 'GET',
url: 'system/modules/countries.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function (data, statut) {
datas.forEach(function (country) {
paths[country.id].data(country);
});
},
error: function (data, statut, erreur) {
console.log(statut);
}
});

Format JSON from controller for use by a plugin

I'm getting a JSON string from my controller:
public ActionResult Highlight()
{
var statesHighlight =
db.Jobs
.Select(r => r.Location);
return Json(statesHighlight , JsonRequestBehavior.AllowGet);
}
I'm getting it via an Ajax request like so:
$.ajax({
async: false,
url: '#Url.Action("Highlight", "Jobs1")',
data: JSON.stringify(),
type: 'POST',
success: function (data) {
citydata = data;
}
});
The issue is that this doesn't maintain the format of my string. Calling the controller action shows that it's correctly formatted JSON, but once it comes out of my Ajax request, it's not. Here it is directly from the controller:
["HDQ","HDQ","EVA","HDQ","HDQ","HDQ","EVA","SVF","SVF","SVF","SVF","DFC","DCF","Feedlot","DCF","DCF","DCC","AGNW","AGNW"]
Is there any way that I can ensure that this is the value set to the variable before I pass it along to my plugin?
The plugin I'm using is called ImageMapster. Currently, I have the JSON hard coded for it and it works as intended.
var data = $.parseJSON($('#map-data').text());
var cities = $.parseJSON($('#city-data').text());
$('img').mapster({
mapKey: 'state',
clickNavigate: true,
isSelectable: false,
highlight: false,
onConfigured: function () {
// make the array into a comma-sparated list
var state_list = data.join(',');
var city_list = cities.join(',');
// the 'set' activates the areas
$('img').mapster('set', true, state_list, options = { fillColor: '638EA5' });
$('img').mapster('set', true, city_list, options = { fillColor: 'ffffff' });
}
});
Is your statesHighlight just a simple System.String[] ? then you will get always the plain string array object in your javascript.
But you want something like var a = { data1 : "a", data2 : "b", data3 : "c" };
JSON basically consists of Key & Value. The equivalent of the data type in C# would be Dictionary. You need to pass Dictionary type or any other key&value object when you parse your data to Json.
public ActionResult Highlight()
{
var statesHighlight =
db.Jobs
.Select(r => r.Location);
// statesHighlight should be Dictionary
// if you want a JSON result having keys and values.
return Json(statesHighlight , JsonRequestBehavior.AllowGet);
}
In case you need just a keyname for the string array, you can set up a keyname like this.
//return Json(statesHighlight , JsonRequestBehavior.AllowGet);
return Json(
new {
keyname = statesHighlight
}
, JsonRequestBehavior.AllowGet
);
I was looking the wrong place entirely for an answer. The formatting was just fine; I discovered this when I took a closer look at the formatting of the variables I was originally using. As it turns out, I was making things more complicated than they needed to be. Bypassing one of my incremental steps ended up being the right solution. Here is my final code:
//retrieve JSON strings from controller
var citydata = {};
$.ajax({
async: false,
url: '#Url.Action("Highlight", "Jobs1")',
method: 'GET',
success: function (data) {
citydata = data;
}
});
var statedata = {};
$.ajax({
async: false,
url: '#Url.Action("HighlightState", "Jobs1")',
method: 'GET',
success: function (data) {
statedata = data;
}
});
//imagemapster to generate map behaviors
$('img').mapster({
mapKey: 'state',
clickNavigate: true,
isSelectable: false,
highlight: false,
onConfigured: function () {
// make the array into a comma-sparated list
var state_list = statedata.join(',');
var city_list = citydata.join(',');
// the 'set' activates the areas
$('img').mapster('set', true, state_list, options = { fillColor: '638EA5' });
$('img').mapster('set', true, city_list, options = { fillColor: 'ffffff' });
}
});

FullCalendar: Using JSON feed containing a dynamic quantity of event sources

I have a case where I need to display multiple eventSources on a calendar, but don't know the quantity of sources until runtime. I've created a javascript function with an AJAX call to a PHP script to create a valid JSON feed (verified with an online tool), and am trying to drop that JSON data into the initialization of the calendar. I've tried it with FullCalendar 1.6.4 and 2.0.0 and it doesn't display any events or throw any errors. The odd part is I can copy the stringified version of the JSON feed into the eventSources and it works. Any ideas?
Here's the stringified JSON data:
[
{
"url": "/s/events.php?e=7",
"type": "GET",
"color": "#ffcc00",
"textColor": "#000000"
},
{
"url": "/s/events.php?e=59",
"type": "GET",
"color": "#ff6600",
"textColor": "#ffffff"
}
]
Heres the FullCalendar initialization code with the JSON data (dataSources not stringified):
function loadCal(dataSources) {
$('#calendar').fullCalendar({
eventSources: [
dataSources // Here's the JSON data
],
editable: true,
...
}
I've tried using the stringified version of dataSources and that results in an unusable URL (e.g., test.com/[%7B%22url%22:%20%22/s/events.php?e=7%22,%22type%22:%20%22GET%22,%22color%22:%20%22).
I'm open to suggestions of alternate approaches. Thanks.
Here's the code as I updated following the suggestion by Bhutto:
function loadCal() {
$('#calendar').fullCalendar({
eventSources: [
function() {
var userData = $.ajax( {
url: '/s/calendar_userdata.php',
method: 'GET',
dataType: 'json',
success: function(userData) {
//console.log(userData);
var user_count = userData.length;
var source = [];
var jsonData = [];
// Create the sources
for (var i = 0; i < user_count; i++)
{
var uid = userData[i].uid;
if(!source[i]) source[i] = [];
source[i] = '/s/events.php?e=' + uid;
// Add each source to a JSON feed object
jsonData.push({
url: source[i],
type: 'GET',
color: userData[i].cal_color,
textColor: userData[i].txt_color,
error: function() { alert('There was an error loading calendar data.');}
});
}
console.log(jsonData); // In the console I can see well formed JSON data
return jsonData;
}
});
}
],
editable: true,

Categories

Resources