I am working on simple task read the data from url which is in JSON format and display those fields in Table
i written code like as
var Win = Titanium.UI.currentWindow;
//SEARCH BAR
var xhr = Titanium.Network.createHTTPClient();
tableData=[];
Win.open();
xhr.onload = function() {
alert('res'+this.responseData);
var json = this.responseText;
var response = JSON.parse(json);
//-- Mail was sent
alert('respoinse length : '+response.result.length);
tableData=[];
for (i = 0; i < response.result.length; i++) {
sresult = response.result[i];
//alert('City'+ sresult.city);
var row = Ti.UI.createTableViewRow({
rowID: i,
color:'#222',
left:70, top:44,
width:360,
text:sresult.County
});
tableData.push(row);
}
table.setData(tableData);
};
var table = Titanium.UI.createTableView({
top:60,
data:tableData
});
Win.add(table);
//xhr.open('GET', 'https://www.clia.livestockid.ca/CLTS/public/division/CCIA/en/splash_logo.jpg');
xhr.open('GET', 'http://gomashup.com/json.php?fds=geo/usa/zipcode/city/STERLING');
xhr.send();
i run it on Titanium - the first alert showing the JSON data. after that its not getting alert of second one not sure ... why its not moving to next step... please help me on this is there any mistakes in code or else parsing issue.
Thanks
Devendar
The "JSON" returned by the url you gave (http://gomashup.com/json.php?fds=geo/usa/zipcode/city/STERLING) is invalid. (http://jsonlint.com is a useful resource for checking that sort of thing.) It starts with a ( and ends with a ), like this:
({
"result":[
{
"Longitude" : "-071.939375",
"Zipcode" : "01564",
"ZipClass" : "STANDARD",
"County" : "WORCESTER",
"City" : "STERLING",
"State" : "MA",
"Latitude" : "+42.366765"
}
]}
)
(I've omitted a lot from that.)
JSON documents start with either [ or {, and end with the corresponding ] or }.
The above would be valid without the ( at the beginning and ) at the end, so you could always remove them before parsing, but the real answer is to fix the feed.
Related
Edit 3: The code is now working across numerous objects (thanks to Noam) and he has also helped in getting the random function working alongside it. I'll update the code in the question once its implemented.
Edit 2: I've taken #Noam Almosnino's answer and am now trying to apply it to an Array with numerous objects (unsuccessfully). Here's the Remix link. Please help!
Edit: I've taken some feedback and found this page which talks about using a JSON.parse function. I've edited the code to reflect the new changes but I still can't figure out exactly whats missing.
Original: I thought this previous answer would help in my attempt to parse a json file and return a random string and its related pair (e.g Title-Platform), but I couldn't get it to work. My goal is to render the output as a text item in my scene. I've really enjoyed working with A-frame but am having a hard time finding documentation that can help me in this regard. I tried using the following modified script to get text from the Json file...
AFRAME.registerComponent('super', { // Not working
schema: {
Games: {type: 'array'},
jsonData: {
parse: JSON.parse,
stringify: JSON.stringify}
},
init: function () {
var el = this.el;
el.setAttribute('super', 'jsonData', {src:"https://cdn.glitch.com/b031cbf1-dd2b-4a85-84d5-09fd0cb747ab%2Ftrivia.json?1514896425219"});
var hugeArray = ["Title", "Platform",...];
const el.setAttribute('super', {Games: hugeArray});
el.setAttribute('position', {x:-2, y:2, z:-3});
}
});
The triggers are also set up in my html to render the text. My code is being worked on through glitch.com, any help will be much appreciated!
To load the json, I think you need to use an XMLHttpRequest (as Diego pointed out in the comments), when that's loaded, you can set the text through setAttribute.
Here's a basic example on glitch:
https://glitch.com/edit/#!/a-frame-json-to-text
On init it does the request, then when done, it set's the loaded json text onto the entity.
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsonText = JSON.parse( event.target.response )
textEntity.setAttribute("value", jsonText.text)
} );
request.send( null );
}
});
Updated version: https://glitch.com/edit/#!/peppermint-direction
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var games = JSON.parse( event.target.response ).games;
// Get a random game from the list
var randomGame = games[Math.floor(Math.random()*games.length)];
// Get the next game if it's available
var nextGame = null
if (games.indexOf(randomGame) < games.length - 1) {
nextGame = games[games.indexOf(randomGame) + 1]
}
// Build the string for the games
var gameInfo = randomGame.Title + '\n' + randomGame.Developer + '\n\n'
if (nextGame != null) {
gameInfo += nextGame.Title + '\n' + nextGame.Developer + '\n'
}
textEntity.setAttribute("value", gameInfo);
var sceneEl = document.querySelector('a-scene');
sceneEl.querySelector('a-box').setAttribute('material', {src:"https://cdn.glitch.com/4e63fbc2-a1b0-4e38-b37a-9870b5594af8%2FResident%20Evil.jpg?1514826910998"});
});
request.send( null );
}
});
I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?
Here's my code.
Parse.Cloud.httpRequest({
url: 'http://myservicehost.com',
headers: {
'Authorization': 'XXX'
},
success: function(httpResponse) {
console.log("Success!");
var json = JSON.parse(httpResponse.text);
var recipes = json.results;
for(int i=0; i<recipes.length; i++) {
var Recipe = Parse.Object.extend("Recipe");
var recipeFromJSON = recipes[i];
// how do i save recipeFromJSON into Recipe without setting all the fields one by one?
}
}
});
I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.
for(int i=0; i<recipes.length; i++) {
var recipeFromJSON = recipes[i];
recipeFromJSON.className = "Recipe";
var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
// do stuff with recipeParseObject
}
Example from this page https://parse.com/docs/js/guide
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
score: 1337,
playerName: "Sean Plott",
cheatMode: false
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
IHMO this question is not a duplicate of How to use Parse.Object fromJSON? [duplicate]
In this question the JSON has not been generated by the Parse.Object.toJSON function itself, but comes from another service.
const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';
Parse.Object.fromJSON(asJson);
// Without L3 this results into:
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible
I am using jsplumb go show pictorial view of all devices connected to switch. I am following below approach, please comment in case if it's not as per standard.
Creating map of all the devices which are connected in the network, and dynamically create all devices on screen using innerHtml.
Create mapping json which contain which devices are connected to which device.
I now iterate json using javascript and create source and target for all devices on screen.
Problem:
When I iterate through json, source and target is not able to set in the below code.
var result = JSON.parse(devicePaths);
for (var i in result) {
var _source = new String(result[i]["source"]);
var _target = new String(result[i]["target"]);
var _endpoint = new String(result[i]["endpoint"]);
console.log('_source ' + _source); //this gives me proper value
console.log('_target ' + _target); //this gives me proper value
console.log('_endpoint ' + _endpoint);
instance = jsPlumb.getInstance({
PaintStyle : {
lineWidth : 1,
strokeStyle : "#567567",
outlineColor : "black",
outlineWidth : 1
}
});
common = {
anchors : [ "BottomCenter", "BottomCenter" ],
endpoints : [ "Dot", "Blank" ]
}
instance.connect({
source : _source,
target : _target,
detachable : false,
endpoint : _endpoint
}, common);
instance.draggable(_source);
}
});
Same works if I hardcode source and target values as source : rx_1 and target masterSwitch.
Hello I have a JQuery/Ajax function as following:
$.ajax({
type : "POST",
url : "/posts/getids",
success: function(response){
console.log(response);
},
error: function() {
alert('An unexpected error has occurred! Please try later.');
}
});
In my cakePHP script I'm sending an array using the json_encode($array) function.
In firebug I get this result :
[{"Post":{"id":1}},{"Post":{"id":2}},{"Post":{"id":4}},{"Post":{"id":3}}]
So my question is How can I simply print only the ids like this : 1, 2, 3, 4
Thank you.
// Convert JSON to JavaScript array.
var dataFromServer = JSON.parse(response);
// Creating an array of id's.
var idArray = [];
// Moving data to "idArray".
for(i = 0; i < dataFromServer.length; i++){
idArray[i] = dataFromServer[i].Post.id;
}
// Checking the result.
console.log(idArray);
// [1, 2, 3, 4].
This seems like it should be simple. Here is my data store declaration:
var dataStore = new Ext.data.JsonStore({
autoLoad : true,
url : '#mvclink(' json.getCostReportsJsonData ')#&layout_type=txt',
root : 'data',
id : 'dataStoreId',
fields : ['project', 'cost']
});
The url is actually generated by ColdFusion, which calls the query and converts it to Json format. I think everything works correctly here, because the Json object comes back as:
{"recordcount":1,"columnlist":"project,cost","data":[{"project":"ABC","cost":2250}]}
I have dummy data in there for now, so just one row is returned.
Next, I declare an Ext.Panel with a DataView in it:
var myPanel = new Ext.Panel({
layout : 'fit',
id : 'myPanel',
title : "My Panel",
monitorResize : true,
deferredRender : false,
items : new Ext.DataView({
store : dataStore,
tpl : costReportTemplate
}),
renderTo : Ext.getBody()
});
The template referenced is an XTemplate:
var costReportTemplate = new Ext.XTemplate(
'<tpl for=".">',
'<p><b>{project}</b>: {cost:this.format}</p>',
'</tpl>', {
format : function (v) {
var s = Ext.util.Format.usMoney(v);
return s.substring(0, s.indexOf('.'));
}
});
Upon rendering the page, I can see the panel, but it's completely empty, and I get no errors in Firebug. What am I doing wrong?
I figured it out! I hadn't used a dummy cost value with a decimal point, so the format function wasn't working properly. I wasn't getting any errors, though. I changed it to check if (s.indexOf('.') != -1) and everything is fine now.