Getting Json formatted objects - json

Ok, so I have a big JSON file that has arrays and objects setup for controls for a google map project I am working on...looks like this:
{
"settings":
{
"DEFAULT_MAP_SETTING": "DEFAULT_MAP_SETTINGS",
"DEFAULT_MAP_RES": "county",
"DEFAULT_MAP_CAT": "popden"
},
"map_settings":
{
"DEFAULT_MAP_SETTINGS":
{
"map_options":
{
"center": [39.828175, -94.5795],
"mapTypeId": "TERRAIN",
"streetViewControl": false,
"scrollwheel": false,
"overviewMapControl": false,
"mapTypeControl": false,
"zoom": 4
},
"map_bounds":
{
"upper-left": [98.70, -127.50],
"lower-right": [48.85, -55.90]
},
}
}
}
My question is how do I go about getting this data in json format as it has to be in json format to load up options and what not in google maps. For instance I have
var myMapOptions = {
"zoom": 4,
"minZoom" : 4,
"scrollWheel" : false,
"center": initialLoc,
"mapTypeId": google.maps.MapTypeId.ROADMAP,
};
var theMap = new google.maps.Map(document.getElementById("map_canvas"), myMapOptions);
Which loads up the google map. But I cant figure out how to set myMapOptions with my big Json file. Every method that I know of returns the json data in strings and gets rid of the formatting. Like $.ajax in jQuery will go get the json for me but it strips it of its formatting.
Can anyone help me out?

jQuery $.ajax() will automatically transform you JSON "file" into a javascript object if your request come back with a JSON header.
However you can override this by using dataType of $.ajax:
$.ajax({
url: "test.html",
dataType: "text",
success: function(data){
alert(data);
}
});
The previous script will alert you JSON file like you want.
[Update]
You can try to use eval():
$.ajax({
url: "test.html",
dataType: "text",
success: function(data){
var options = eval(data);
}
});
In this case your data need to be executable by javascript.
[Update 2]
JsonP style, your json file need to looks like that:
var options = {
"zoom": 4, "minZoom" : 4,
"scrollWheel" : false,
"center": new google.maps.LatLng(39.828175, -94.5795),
"mapTypeId": google.maps.MapTypeId.ROADMAP
};
Notice the "var options ="
Your ajax request need to look like that:
$.ajax({
url: "test.html",
dataType: "text",
success: function(data){
alert(data);// will show your data as text
eval(data); this will execute your "JSON file"
//after eval you can now use options as a variable
alert(options);
}
});

Related

How to get this data with AJAX from JSON?

I was using this code below to get the title/artist data from an old-station (https://stream.mydnic.be/status-json.xsl) with ajax:
(function worker() {
$.ajax({
url: host + '/status-json.xsl',
success: function(data) {
artist = data.icestats.source.artist;
title = artist + ' - ' + data.icestats.source.title;
document.title = title;
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 3000);
}
});
Now I changed the station and the new one use another JSON file that looks a little different:
"id": "station_name",
"songs":[
{
"title": "Water Silence",
"artist": "Solar Fields",
"album": "Fahrenheit Project Part Five",
"albumart": "",
"date": "1569618168"
},
The problem is that now, I get 'undefined' on Title and artist with the first Ajax Code.
So, I would like to ask if someone knows what I need to change on the first ajax code to work with the new JSON file and get the title/artist data correctly.
I really appreciate your help.
You are trying to get an attribute from an object when it is a list of objects, what you have to do is iterate the array or get the result by index.
Like this:
(function worker() {
$.ajax({
url: host + '/status-json.xsl',
success: function(data) {
//In this example you getting element by index
artist = data.songs[0].artist;
title = data.songs[0].title;
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 3000);
}
});

Full Calendar feed with JSON ( Getting data from a restfull webservice )

i have this situation.
I need to use fullCalendar 3.8 to show some reservations.
I have the back end that give me the data in JSON format ( i have about 10 fields ).
In front-end i have a JSP that inlcude fullcalendar, moment and jquery. I need to populate my FullCalendar.
Example the Json that i have is in this form:
[
{
"idReservation": 21,
"idUser": 2,
"idSale": 1,
"timeStart": 1513839600000,
"timeEnd": 1513850400000
},
{
"idReservation": 22,
"idUser": 1,
"idSale": 1,
"timeStart": 1513854000000,
"timeEnd": 1513857600000
} ]
Someone can tell me where can i start to study, make test in the way to feed my calendar with this data ?
i have try to read a lot of articles but cause i am not a Front-End developer i am loosing around :)
The Javascript code that i created is this one:
$(document).ready(function() {
var value=2;
returnReservationsCalendar(value);
});
function returnReservationsCalendar(value){
var serviceEndpoint =
'http://localhost:8080/sale/'+value+'/reservations';
$.ajax({
type : 'GET',
url: serviceEndpoint,
dataType: 'json',
contentType : 'application/json',
success: function (result) {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2014-11-13',
editable: true,
eventLimit: true, // allow "more" link when too many events
events: function (start, end, timezone, callback) {
var events = [];
$.each(result, function (index) {
events.push({
"title": "Event " + index,
"start": result[index].timeStart.toISOString(),
"end": result[index].timeEnd.toISOString(),
});
});
callback(events);
}
});
},
error: function () { alert('Failed!'); }
});
}
At the JSP i have only this code:
<div id="calendar"></div>
The problem is that i have the json response from ajax but i dont understand where i am making the mistake about populating the calendar with the data from json.
You should be seeing errors in your browser's console similar to this (this is as per Google Chrome, others may vary slightly):
Uncaught TypeError: result[index].timeStart.toISOString is not a
function
Simply this is because timeStart is a string from your JSON, not a momentJS or Date object.
You need to pass it through the momentJS constructor before this will work:
events.push({
"title": "Event " + index,
"start": moment(result[index].timeStart).toISOString(),
"end": moment(result[index].timeEnd).toISOString(),
});
See http://jsfiddle.net/sbxpv25p/166/ for a working demo (using a static event list instead of ajax, but it demonstrates the part which is relevant to this answer.

fetching data from json file with ajax

I am building a sports site and need to acccess the json data that is accessible from http://www.nfl.com/liveupdate/game-center/2012020500/2012020500_gtd.json . On my page I am trying to get this data from an ajax. Here is my script below.
<div id="data"></div>
<script>
$.ajax({
url: 'http://www.nfl.com/liveupdate/game-center/2012020500/2012020500_gtd.json',
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, value) {
$('#data').html(value);
});
},
});
</script>
When I do this i just get "261" on my page. I had assumed i would see all the values.
A lot of this data is nested and everything I read was just saying to do something like the script I have above. There are tons of different keys and values and I'll be trying to get select ones in the future. I have tried var variable = data.home.score; but that just got blank results..
Here is an example of some of the data when indented.
"home":{
"score":{
"1":0,
"2":10,
"3":7,
"4":0,
"5":0,
"T":17
},
Am I going about getting this data completely wrong? Can anyone help me get on the right path? Any insight or link's to answers that may help me would be much appreciated.
The JSON from the URL looks like the following, but I have shortened it for better readability.
{
"2012020500": {
"home": {
"score": {
"1": 0,
"2": 10,
"3": 7,
"4": 0,
"5": 0,
"T": 17
},
"abbr": "NE",
.....
.....
.....
},
"nextupdate": 261
}
The following loop reads key-value pairs from the received JSON and populates the value in '#data' . So for each element it replaces the old one. Since 261 is the last value, it is intact.
$.each(data, function(key, value) {
$('#data').html(value);
});
In order to print all the values in a node, it is required to dynamically create elements.
$.each(home, function(key, value) {
$('#data').append("<div>"+value+"<div>");
});
To get the scores, need to fetch the 'score' node and read the values like the following.
$.ajax({url: 'http://www.nfl.com/liveupdate/game-center/2012020500/2012020500_gtd.json',
dataType: 'json',
success: function(data) {
var score= data["2012020500"].home.score;
$.each(score, function(key, value) {
$('#data').append("<div>"+key+" - "+value+"<div>");
});
}
});

extjs error on filling store

I have a java map. I converted it to json string and I obtain something like this :
{"NEW ZEALAND":"111111111111111","CHAD":"1","MOROCCO":"111","LATVIA":"11"}
Now I want to use it in a store and then a chart like the following code but it's not working. I have no error just no display.
var obj = Ext.Ajax.request({
url: App.rootPath + '/controller/home/dashboard/test.json',
method:'GET',
success: function(response) {
return Ext.JSON.decode(response.responseText);
}
});
var store2 = Ext.create('Ext.data.Store', {
model: 'PopulationPoint',
data: obj
});
Ext.create('Ext.chart.Chart', {
renderTo: 'infos2',
width: 500,
height: 300,
store: store2,
series: [
{
type: 'pie',
field: 'population',
label: {
field: 'state',
display: 'rotate',
font: '12px Arial'
}
}
]
});
The AJAX request is asynchronous. As such, the obj variable used to initialize your data won't contain your data yet.
One option is to create the store2 variable and create the chart directly in the success callback of the AJAX request.
A cleaner option would be to configure the store with a proxy to load the url, and in the callback create the chart.
EDIT
The JSON response does not contain the fields that are declared in your model (sent in the comments). Update the JSON to return a properly formatted model and the chart should work as seen in this fiddle. The JSON should look something like
[
{
"state" : "New Zealand",
"population" : 111111111
},
{
"state" : "Chad",
"population" : 1
}
]

Dojo ItemFileWriteStore not reading JSON server file

I am using Dojo and it's dojo/data/ItemFileWriteStore module to read a JSON data file on my local server. In my .js file I have
var myDataStore = new ItemFileWriteStore({
url: "app/data/mydata.json",
handleAs: "json",
clearOnClose: true,
urlPreventCache: true
})
This is located in the postCreate function for my return declare function... so:
define([
"dojo/_base/declare",
"com/cayuse/base/_widget",
"dojo/text!./templates/myform.html",
...
"dojo/data/ItemFileWriteStore",
"dojo/store/DataStore",
"dojo/store/Observable",
"dojo/data/ObjectStore",
"dojo/domReady!"
],
function(declare, widget, template, ..., ItemFileWriteStore, DataStore,
Observable, ObjectStore){
return declare("app.myform", widget, {
templateString: template,
postCreate: function(){
domConstruct.create("link",{
type: "text/css",
rel: "stylesheet",
href: require.toUrl('dojox/form/resources/CheckedMultiSelect.css')
}, document.getElementsByTagName("head")[0]);
// data store
var myDataStore = new ItemFileWriteStore({
url: "app/data/mydata.json",
handleAs: "json",
clearOnClose: true,
urlPreventCache: true
})
console.log(myDataStore);
}
});
}
);
I can change the data store access from what you see above using IFWS method to
var myDataStore = dojo.xhrGet({
url: "app/data/mydata.json",
handleAs: "json",
load: function(data, ioArgs){
console.log(data);
}
});
and it finds the file with no problems.
This is so bizarre! Any ideas on what is going wrong here?
UPDATED:
Here is the data in the file I am reading. I believe it conforms to the JSON format. Let me know if not. xhrGet reads it fine.
{ "identifier": "id",
"label": "firstName",
"items":[
{"id":"0","firstName":"Robert","website":"www.barker.com","email":"robert#barker.com","bday":"1928-08-09","color":"Blue","toolkits":["Dojo","Moo"],"sendEmail":["on"],"format":"HTML"},
{"id":"1","firstName":"Vanna","website":"www.white.com","email":"vanna#white.com","bday":"1968-07-23","color":"Green","toolkits":["Dojo","jQuery"],"sendEmail":["off"],"format":"Text"}
]
}
ItemFileWriteStore requires your data being structured into something like this:
{ identifier: 'abbr',
label: 'name',
items: [
{ abbr:'ec', name:'Ecuador', capital:'Quito' },
{ abbr:'eg', name:'Egypt', capital:'Cairo' },
{ abbr:'sv', name:'El Salvador', capital:'San Salvador' },
{ abbr:'gq', name:'Equatorial Guinea', capital:'Malabo' },
{ abbr:'er', name:'Eritrea', capital:'Asmara' },
{ abbr:'ee', name:'Estonia', capital:'Tallinn' },
{ abbr:'et', name:'Ethiopia', capital:'Addis Ababa' }
]}
That is 'identifier' being your "ID" field, 'label' being your "label" field and then all your objects inside an array called "items".
You can check it out here in ItemFileWriteStore's documentation. If you don't have your JSON data structured like that it's possible that you may end up reading your file with the IFWS and actually not reading any data.
There are other store implementations in dojo 1.7 that don't require such structure, e.g. Memory Store that you can combine with other file reading techniques to achieve the same.
Try using dojo.data.ItemFileReadStore for reading
json data files, instead of dojo/data/ItemFileWriteStore.
Note that dojo.data.ItemFileWriteStore is used for writting json data.
If your code is EXACTLY as you posted it above then the interpreter might not like the fact that you omitted the semicolon from the ItemFileWriteStore assignment. Try adding the ';' as below:
// data store
var myDataStore = new ItemFileWriteStore({
url: "app/data/mydata.json",
handleAs: "json",
clearOnClose: true,
urlPreventCache: true
});
console.log(myDataStore);