json not loading in iphone device while using sencha touch and phonegap - json

I'm trying to load a json into my view. Im using phonegap with sencha touch and when I load the app to my phone the json does not load at all.. It works fine in the browser and in the simulator.
I would really appreciate some help from the experts
Here is the main code that im trying:
the store:
App.stores.freebees = new Ext.data.Store({
model: 'Freebee',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'fixtures/freebees',
reader: {
type: 'json'
}
}
});
the list view:
App.views.FreebeesList = Ext.extend(Ext.List, {
id: 'indexlist',
layout: 'fit',
store: App.stores.freebees,
itemTpl: '{companyName}, {title}, {address}',
listeners: {
'itemtap': function(list, index, item, obj) {
Ext.dispatch({
controller: 'Freebee',
action: 'showDetails',
id: list.getRecord(item).data.id,
lat: list.getRecord(item).data.lat,
longitude: list.getRecord(item).data.longitude,
companyName: list.getRecord(item).data.companyName,
address: list.getRecord(item).data.address,
});
}
},
initComponent: function() {
App.views.FreebeesList.superclass.initComponent.apply(this, arguments);
}
});
Ext.reg('App.views.FreebeesList', App.views.FreebeesList);
the json:
[
{
"id": 1,
"title": "Freebee 1",
"companyName": "Företaget AB 1",
"address": "Ekuddsvägen 1 Nacka 131 38 Sweden",
"lat": 59.3058,
"longitude": 18.1463
},
{
"id": 2,
"title": "Freebee 2",
"companyName": "Företaget AB 2",
"address": "Ekuddsvägen 2 Nacka 131 38 Sweden",
"lat": 59.305,
"longitude": 18.1478
}
]

From my limited experiece with ST so far, you cant load a file which is on the device like that. You may have to load the json file using a script tag and pass it in as data.
data = [ { "id": 1, "title": "Freebee 1", "companyName": "Företaget AB 1", "address": "Ekuddsvägen 1 Nacka 131 38 Sweden", "lat": 59.3058, "longitude": 18.1463 }, { "id": 2, "title": "Freebee 2", "companyName": "Företaget AB 2", "address": "Ekuddsvägen 2 Nacka 131 38 Sweden", "lat": 59.305, "longitude": 18.1478 } ];
then load it into your store like so:
App.stores.freebees = new Ext.data.Store({ model: 'Freebee', root:data, autoLoad: true, proxy: { type: 'ajax', url: 'fixtures/freebees', reader: { type: 'json' } } });
(added root:data)

I had a similar error.. Please see my question and answer here:
Sencha parses JSON in iphone simulator, but not on iPhone - phonegap

Related

Parsing objects of a JSON for input validation

I want to use a database of valid ICAO and IATA airport codes for a discord bot input in typescript. However, I am not quite sure how to call the "icao" and "iata" contstructor of all objects, as each one is defined differently and there are thousands: e.g.:
"00AK": {
"icao": "00AK",
"iata": "",
"name": "Lowell Field",
"city": "Anchor Point",
"state": "Alaska",
"country": "US",
"elevation": 450,
"lat": 59.94919968,
"lon": -151.695999146,
"tz": "America\/Anchorage"
},
"00AL": {
"icao": "00AL",
"iata": "",
"name": "Epps Airpark",
"city": "Harvest",
"state": "Alabama",
"country": "US",
"elevation": 820,
"lat": 34.8647994995,
"lon": -86.7703018188,
"tz": "America\/Chicago"
},
The bot uses the following to provide the METAR of a specific airport:
name: 'metar',
description: 'Provides the METAR report of the requested airport',
category: CommandCategory.UTILS,
executor: async (msg) => {
const splitUp = msg.content.replace(/\.metar\s+/, ' ').split(' ');
if (splitUp.length <= 1) {
await msg.reply('please provide an ICAO airport code.');
return Promise.resolve();
}
const icaoArg = splitUp[1];
if (icaoArg.length !== 4) {
await msg.reply('please provide an ICAO airport code.');
return Promise.resolve();
}
request({
method: 'GET',
url: `https://avwx.rest/api/metar/${icaoArg}`,
headers: {
Authorization: process.env.METAR_TOKEN },
}, async (error, response, body) => {
const metarReport = JSON.parse(body);å
const metarEmbed = makeEmbed({
title: `METAR Report | ${metarReport.station}`,
description: makeLines([
'**Raw Report**',
metarReport.raw,
,
'**Basic Report:**',
`**Time Observed:** ${metarReport.time.dt}`,
`**Station:** ${metarReport.station}`,
`**Wind:** ${metarReport.wind_direction.repr} at ${metarReport.wind_speed.repr}kts`,
`**Visibility:** ${metarReport.visibility.repr}${metarReport.units.visibility}`,
`**Temperature:** ${metarReport.temperature.repr}C`,
`**Dew Point:** ${metarReport.dewpoint.repr}C`,
`**Altimeter:** ${metarReport.altimeter.value.toString()} ${metarReport.units.altimeter}`,
]),
fields: [
{
name: 'Unsure of how to read the raw report?',
value: 'Type \'**.metarhow**\' to learn how to read raw METARs',
inline: false
},
],
footer: { text: 'This METAR report may not accurately reflect the weather in the simulator. However, it will always be similar to the current conditions present in the sim.' },
});
await msg.channel.send({ embeds: [metarEmbed] });
});
},
};
Currently, if a user provides an ICAO that's not valid the bot crashes, or if they provide a valid IATA, the discord api throws the user an error to provide a valid ICAO code. How would I go about cross referencing the user argument with the JSON so the bot does not crash when inputting an invalid ICAO? Thanks

Using datatables when returning json objects

I want to use datatable to return JSON from txt or some web api.
So, everything works well if data is in following format (coopInformation.txt):
{
"data": [
{
"employer": "Unisys",
"degree": "NETSYS-MS",
"city": "Blue Bell PA",
"term": "20151"
},
{
"employer": "Paychex Inc",
"degree": "INFOST-MS",
"city": "Rochester NY",
"term": "20151"
},
{
"employer": "Paychex Inc",
"degree": "INFOST-MS",
"city": "Rochester NY",
"term": "20151"
}
]
}
This is my jquery call:
$(document).ready(function() {
$('#example').DataTable({
ajax: 'ajax/data/coopInformation.txt',
columns: [
{
data: 'employer'
},
{
data: 'degree'
},
{
data: "city"
},
{
data: "term"
}
]
});
});
But when json object don't start with "data", for example starts with "coopInformation", this call returns an error even if I change columns to coopInformation:
$(document).ready(function() {
$('#example').DataTable({
ajax: 'ajax/data/coopInformation.txt',
columns: [
{
coopInformation: 'employer'
},
{
coopInformation: 'degree'
},
{
coopInformation: "city"
},
{
coopInformation: "term"
}
]
});
});
Uncaught TypeError: Cannot read property 'length' of undefined
at jquery.dataTables.min.js:65
at h (jquery.dataTables.min.js:51)
at Object.success (jquery.dataTables.min.js:52)
at fire (jquery-3.5.1.js:3496)
at Object.fireWith [as resolveWith] (jquery-3.5.1.js:3626)
at done (jquery-3.5.1.js:9786)
at XMLHttpRequest. (jquery-3.5.1.js:10047)
It looks like this libs are predefined to use "data" or I am wrong...
My question is: how to make a simple call like this using something else but not "data". On datatables web, all examples are used with this "data".
Kind regards,
Milan

How to bind json data to screen with tpl config?

I'm working on Sencha's Admin Dashboard sample and trying to customize 'Weather' panel.
I've created a JSON format url with OpenWeatherMap's Current weather data API. The thing I can't bind JSON data to Weather panel with tpl config. I've created a ViewModel and called it within Component but it did not worked as well.
Here is the component class;
Ext.define('OWeb.view.dashboard.Weather', {
extend: 'Ext.Component',
xtype: 'weather',
baseCls: 'weather-panel',
border: false,
height: 80,
store: {
proxy: {
type: 'ajax',
url: 'http://api.openweathermap.org/data/2.5/weather?q=Antalya,TR&appid=9b59049894d42af608baf69f869b9ace&units=metric',
reader: {
type: 'json'
}
},
autoLoad: true
},
tpl: '<div class="weather-image-container"><img src="resources/img/{icon}" alt="{weather.description}"/></div>'+
'<div class="weather-details-container">' +
'<div>{main.temp}°</div>' +
'<div>{weather.main}</div>' +
'</div>'
});
And this is link for JSON data which returns via OpenWeatherMap and snippet;
{
"coord": {
"lon": 30.72,
"lat": 36.77
},
"weather": [{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}],
"base": "stations",
"main": {
"temp": 25,
"pressure": 1015,
"humidity": 23,
"temp_min": 25,
"temp_max": 25
},
"visibility": 10000,
"wind": {
"speed": 5.7,
"deg": 320
},
"clouds": {
"all": 0
},
"dt": 1507184400,
"sys": {
"type": 1,
"id": 6028,
"message": 0.0025,
"country": "TR",
"sunrise": 1507175759,
"sunset": 1507217657
},
"id": 323776,
"name": "Antalya",
"cod": 200
}
Thanks, any advice is welcome.
UPDATE
I've found this post and I tried same thing; extend from Ext.DataView, setting proxy type jsonp and using itemTpl config. Now I can bind to JSON data but only can displaying {main.temp}. Any idea please?
Ext.define('OWeb.view.dashboard.Weather', {
//extend: 'Ext.Component',
extend: 'Ext.DataView',
xtype: 'weather',
baseCls: 'weather-panel',
border: false,
height: 80,
store: {
proxy: {
type: 'jsonp',
url: 'http://api.openweathermap.org/data/2.5/weather?q=Antalya,TR&appid=9b59049894d42af608baf69f869b9ace&units=metric',
reader: {
type: 'json'
}
},
autoLoad: true
},
itemTpl: '<div class="weather-image-container"><img src="{weather.icon}" alt="{weather.description}"/></div>'+
'<div class="weather-details-container">' +
'<div>{main.temp}°</div>' +
'<div>{weather.description}</div>' +
'</div>'
});
Please look at the points below to understand this.
Ext.Component class does not work with store because of which your code was not working. You could have created the store elsewhere and then retrieved the data from store and set the data property of the component to it. (Note that for Ext.Component, the tpl property works with data property:
var data = store.getData();
component.setData(data);
jsonP proxy is needed only when you need to fetch data from a different domain.
If you are getting data in a store then better option is to extend your class from Ext.DataView because it works with store.
The values were not properly showing in the template because weather property was an array of objects and we needed something like weather[0].icon. So for this, Model was required with fields properly mapped.(Look at the mapping property.)
I have created a Fiddle for your code. Image is not showing because url is not returning any image. Rest is working. Hope this is helpful to you.

What is the best method to seeding a Node / MongoDB application?

So, I'm new to the MEAN stack, and I've hit a wall trying to seed MongoDB. I'm using Mongoose to communicate with the database, and there's a bunch of documentation suggesting I should be able to seed using populated JSON files.
What I've tried:
node-mongo-seed; Pretty straight forward, but consistently throws errors on the end of arrays. (Perhaps the missing bson module is at fault?)
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
Seeding files from directory /Users/Antwisted/code/wdi/MEAN/seeds
----------------------
Seeding collection locations
err = [SyntaxError: /Users/Antwisted/code/wdi/MEAN/seeds/locations.json: Unexpected token {]
mongoose-seed; Also pretty straight forward, basically puts the JSON objects into a variable before exporting to the database. Promising, but... more errors...
Successfully initialized mongoose-seed
[ 'app/models/locationsModel.js' ]
Locations collection cleared
Error creating document [0] of Location model
Error: Location validation failed
Error creating document [1] of Location model
Error: Location validation failed
Error creating document [2] of Location model
Error: Location validation failed...
So, my thoughts were that it was probably a syntax error within the JSON structure, but playing around with that has not yielded any real solutions (or maybe I'm missing it?). Sample of my JSON:
{
{
"header": "Dan's Place",
"rating": 3,
"address": "125 High Street, New York, 10001",
"cord1": -73.0812,
"cord2": 40.8732,
"attributes": ["Hot drinks", "Food", "Premium wifi"],
"hours": [
{
"days": "Monday - Friday",
"hours": "7:00am - 7:00pm",
"closed": false
},
{
"days": "Saturday",
"hours": "8:00am - 5:00pm",
"closed": false
},
{
"days": "Sunday",
"closed": true
}
],
"reviews": [
{
"rating": 4,
"id": ObjectId(),
"author": "Philly B.",
"timestamp": "new Date('Feb 3, 2016')",
"body": "It was fine, but coffee was a bit dull. Nice atmosphere."
},
{
"rating": 3,
"id": ObjectId(),
"author": "Tom B.",
"timestamp": "new Date('Feb 23, 2016')",
"body": "I asked for her number. She said no."
}
]
},
{
"header": "Jared's Jive",
"rating": 5,
"address": "747 Fly Court, New York, 10001",
"cord1": -73.0812,
"cord2": 40.8732,
"attributes": ["Live Music", "Rooftop Bar", "2 Floors"],
"hours": [
{
"days": "Monday - Friday",
"hours": "7:00am - 7:00pm",
"closed": false
},
{
"days": "Saturday",
"hours": "8:00am - 5:00pm",
"closed": false
},
{
"days": "Sunday",
"closed": true
}
],
"reviews": [
{
"rating": 5,
"id": ObjectId(),
"author": "Jacob G.",
"timestamp": "new Date('Feb 3, 2016')",
"body": "Whoa! The music here is wicked good. Definitely going again."
},
{
"rating": 4,
"id": ObjectId(),
"author": "Tom B.",
"timestamp": "new Date('Feb 23, 2016')",
"body": "I asked to play her a tune. She said no."
}
]
}
}
Additionally, I'm not entirely sure how to specify subdocuments within the JSON (assuming I can get the seeding process to work correctly in the first place).
Here's my model:
var mongoose = require('mongoose');
var subHoursSchema = new mongoose.Schema({
days: {type: String, required: true},
opening: String,
closing: String,
closed: {type: Boolean, required: true}
});
var subReviewsSchema = new mongoose.Schema({
rating: {type: Number, required: true, min: 0, max: 5},
author: String,
timestamp: {type: Date, "default": Date.now},
body: String
});
var locationSchema = new mongoose.Schema({
name: {type: String, required: true},
address: String,
rating: {type: Number, "default": 0, min: 0, max: 5},
attributes: [String],
coordinates: {type: [Number], index: '2dsphere'},
openHours: [subHoursSchema],
reviews: [subReviewsSchema]
});
mongoose.model('Location', locationSchema);
Any insight on how to navigate these issues would be greatly appreciated. Thanks!
You can populate MongoDB in the CLI using mongoimport
It will load a JSON file into a specified MongoDB Instance & Collection, all you need is for a mongod instance to be running before executing.
Here is a walkthrough of using mongoimport.
You JSON is not flowing your schema.
Fix your JSON to this:
{
{
"name": "Dan's Place",
"rating": 3,
"address": "125 High Street, New York, 10001",
"coordinates": [-73.0812, 40.8732],
"attributes": ["Hot drinks", "Food", "Premium wifi"],
"openHours": [
{
"days": "Monday - Friday",
"opening": "7:00am",
"closing": "7:00pm",
"closed": false
},
{
"days": "Saturday",
"opening": "8:00am",
"closing": "5:00pm",
"closed": false
},
{
"days": "Sunday",
"closed": true
}
],
"reviews": [
{
"rating": 4,
"author": "Philly B.",
"timestamp": "new Date('Feb 3, 2016')",
"body": "It was fine, but coffee was a bit dull. Nice atmosphere."
},
{
"rating": 3,
"author": "Tom B.",
"timestamp": "new Date('Feb 23, 2016')",
"body": "I asked for her number. She said no."
}
]
},
{
"name": "Jared's Jive",
"rating": 5,
"address": "747 Fly Court, New York, 10001",
"coordinates": [-73.0812, 40.8732],
"attributes": ["Live Music", "Rooftop Bar", "2 Floors"],
"openHours": [
{
"days": "Monday - Friday",
"opening": "7:00am",
"closing": "7:00pm",
"closed": false
},
{
"days": "Saturday",
"opening": "8:00am",
"closing": "5:00pm",
"closed": false
},
{
"days": "Sunday",
"closed": true
}
],
"reviews": [
{
"rating": 5,
"author": "Jacob G.",
"timestamp": "new Date('Feb 3, 2016')",
"body": "Whoa! The music here is wicked good. Definitely going again."
},
{
"rating": 4,
"author": "Tom B.",
"timestamp": "new Date('Feb 23, 2016')",
"body": "I asked to play her a tune. She said no."
}
]
}
}
You can use mongoose-data-seed to write your own seed script that interacting your mongoose models with:
https://github.com/sharvit/mongoose-data-seed
I solved this issue on a project by dumping the relevant data to an extended JSON array formatted file using mongoexport --jsonArray, then importing this back into POJO format inside the Node application using the EJSON package. I then just use Mongoose to insert the resulting JS array back into the database using the correct collection model you've created using Mongoose.
The necessary JSON data files to seed the application for a first-run are checked into the application repository.
Here's a quick sample you may be able to adapt to your purposes:
// ...
// 'Items' is the Mongoose collection model.
const itemResult = await Items.find({}).exec();
if(itemResult.length === 0) {
const itemsSeedDataRaw = fs.readFileSync(`${__dirname}/data/items.json`, 'utf8');
const itemsSeedData = EJSON.parse(itemsSeedDataRaw);
await Items.insertMany(itemsSeedData);
}
// ...
I would also recommend looking into mongo-seeding. There is both a JS library version and a CLI version. The motivation for this library is described here.

fullcalendar won't display json feed using eventSource

I'm working with fullcalendar for the first time. it seemed straight forward at first but then problems. Ok I am trying to use eventSource to load multiple sources. It loads all the google calendar sources no problem but the json feed is not being displayed. I'm wondering if its because I'm using a static json file to test or maybe I left out something, or is the json formatted wrong. Do I need to code a json feed in java to test (working with java)? These are the things I've looked at and I've looked at the other links regarding fullcalendar and json and none helped. If someone could give me a little help it would greatly appreciated.
feed.json
{
"events":
[
{
"id": "0",
"title": "Business Lunch",
"start": "2015-09-03T13:00:00",
"end": "2015-09-03T14:00:00",
"constraint": "businessHours"
},
{
"id": "2",
"title": "Conference",
"start": "2015-09-18",
"end": "2015-09-19",
"constraint": "businessHours"
},
{
"id": "3",
"title": "Party",
"start": "2015-09-29T20:00:00",
"end": "2015-09-29T24:00:00",
"constraint": "businessHours"
}
]
}
code sample
eventSources: [
// your event source
//feed source
{
url: '/hairzone/feed.json',
type: 'GET', //GET or POST
dataType: 'json',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
},
// any other sources...
{
googleCalendarId: 'some calendar id',
color: 'pink', // an option!
textColor: 'black', // an option!
//rendering: 'background'
overlay:false
},
// any other sources...
{
googleCalendarId: 'some calendar id',
color: 'blue', // an option!
textColor: 'black', // an option!
rendering: 'background',
overlay:false
}
]
I solved the problem. It seems that the feed is not formatted properly for fullcalendar. It just need everything starting with the brackets. Doesn't matter if its a static file or generated feed.
[
{
"id": "0",
"title": "Business Lunch",
"start": "2015-09-03T13:00:00",
"end": "2015-09-03T14:00:00",
"constraint": "businessHours"
},
{
"id": "2",
"title": "Conference",
"start": "2015-09-18",
"end": "2015-09-19",
"constraint": "businessHours"
},
{
"id": "3",
"title": "Party",
"start": "2015-09-29T20:00:00",
"end": "2015-09-29T24:00:00",
"constraint": "businessHours"
}
]