JSON Parsing in Titanium App (Multidimensional array) - json

I want to parse a multidimensional array in Titanium.
It is something like this:-
{"nodes":
[{"node":
{
"title":"<a href=\"\/adf\/into-the-blue\">Into the Blue<\/a>",
"Teaser":"Into the Blue Teaser.",
"Knowledge":"<a href=fsdf">Americas<\/a>",
...
...
This is what I did. (It only gets the first row :( )
// url has the JSON URL.
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function() {
var response = xhr.responseText;
var resultObj = JSON.parse(response);
Ti.API.log("The Response is " + response);
Ti.API.log("THE RESULT " + resultObj);
updateBanners(resultObj);
updateTable(resultObj, catid, catregion, cattopic, listByDate);
};
xhr.open("GET", url);
xhr.send();
Many Thanks

Perhaps you are missing a piece from the parsing.
var resultObj = JSON.parse(response);
Mine usually looks like.
var resultObj = JSON.parse(response).NameOfMyRemoteFunctionResult;
I use WCF web service for my calls, so this is the type of response I get back.

This is how I was able to solve it.
//Correct Response. Gives the total number of returned Records.
resultObj.nodes.length
// and for a specific title of first row.
resultObj.nodes[0].node["title"]
alert("Total Records are :- "+ responseObjArr.nodes.length + " and the 1st Title is:- " + responseObjArr.nodes[0].node["title"]);

Related

Xamarin get webservice with parameter

i am new with xamarin. I want to add some json data with get web service. I try like following:
var response = await client.GetAsync("myurl" + "?applicationid=" +
applicationId + "?siteid=" + siteId + "?userid=" + userId");
string responseJson = await response.Content.ReadAsStringAsync();
Debug.WriteLine("response:>" + responseJson);
But code not executed after get method.
please anyone help me.
Thanks in advance. :)
Finally got the solution, pass the values with the url itself.
var response = await client.GetAsync("mybaseurl"+"/applicationid/"1"/siteid/"5"/u‌​serid/"+25");

Nodejs read JSON data from a http request chunk

I am using Jira API's to get data on single tickets. I have successfully setup a http GET request to the server and can display the data to the console however I ideally need to get certain properties from the data which is in JSON format.
When I try to read the properties I just get undefined.
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk); // This displays the JSON
console.log('endSTATUS: ' + chunk.id); // This shows up undefined
});
The data is in this format from jira API for reference.
The first console log in the res successfully displays all the data from the chunk.
The second one is:
endSTATUS: undefined
Try to get the body after the data stream finish. Like this:
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
// Data reception is done, do whatever with it!
var parsed = JSON.parse(body);
console.log('endSTATUS: ' + parsed.id);
});
Make sure you are parsing the response data as JSON. I think you may want something like var data = JSON.parse(chunk);, and reference the chunk data as data.value.
res.on('data', function (chunk) {
var data = JSON.parse(chunk);
console.log('BODY: ' + data);
console.log('endSTATUS: ' + data.id);
});

How to update objects using Cloud Code?

I am using Parse Cloud Code for retrieving JSON data from external API. JSON data are updated every 2 min.
To accomplish this, I am using Cloud Job to run my method every 2 minutes to keep data fresh. Also, I am storing whole JSON data to Parse.
When I run this code for the first time everything works well, but... when code runs for second, third or fourth time instead of updating objects it creates the new ones.
How to update objects instead of creating the new ones, when there are some data?
Code:
Parse.Cloud.define("getCars", function(request, response) {
var promise = new Parse.Promise();
var Cars = Parse.Object.extend('Cars');
var query = new Parse.Query(Cars);
query.find().then(function (results){
Parse.Cloud.httpRequest({
method: 'GET',
url: urlLink,
success: function(httpResponse) {
var stations = new Array();
var data = JSON.parse(decodeURIComponent(escape(httpResponse.text))); // utf-8 decode
for (var i = 0; i < data.length; i++) {
var Cars = Parse.Object.extend('Cars'),
car = new Cars(),
content = data[i];
car.set('number', content.number);
car.set('name', content.name);
car.set('address', content.address);
car.set('position', content.position);
car.set('status', content.status);
cars.push(station);
};
Parse.Object.saveAll(cars, {
success: function(objects) {
promise.resolve();
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
promise.reject(error.message);
}
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
promise.reject(error.message);
}
});
});
return promise;
});
SOLUTION
I have finally found the solution. Maybe this will be useful for other people who are facing the same problem.
I added a simple if statement which checks query result. If query does not return data, new object is created, otherwise: old object is filled with new information and saved into database.
station = (results == 0) ? new Stations() : results[i];
you are createting new object car = new Cars(), every time.instead find with objectId and in success response you will get ParseObject list(array).
update first parseObject from that list

Select specific data in JSON output

I've created a function that does a http request and then saves some data from the JSON output.
$scope.addMovie = function() {
'http://api.themoviedb.org/3/movie/206647?api_key=a8f7039633f2065942cd8a28d7cadad4&append_to_response=releases'
// Search for release dates using the ID.
var base = 'http://api.themoviedb.org/3/movie/';
var movieID = $(event.currentTarget).parent().find('.movieID').text()
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var append_to_response = '&append_to_response=releases'
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + movieID + '?api_key=' + apiKey + append_to_response + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function(data, status, headers, config) {
if (status == 200) {
// $scope.movieListID = data.results;
$scope.movieListID = data;
console.log($scope.movieListID);
createMovie.create({
title: $scope.movieListID.original_title,
release_date: $scope.movieListID.release_date,
image: $scope.movieListID.poster_path
}).then(init);
} else {
console.error('Error happened while getting the movie list.')
}
})
};
This function saves the title, release date en posterpath and that works fine. The problem is that it only saves one release_date while the JSON output has a lot more, but I don't know how to acces that.
This is a example of the JSON output I request
It has a release_date, which I save now, but it also has more information,
releases":{
"countries":[
{"certification":"","iso_3166_1":"GB","primary":true,"release_date":"2015-10-26"},
{"certification":"","iso_3166_1":"US","primary":false,"release_date":"2015-11-06"},
{"certification":"","iso_3166_1":"NL","primary":false,"release_date":"2015-11-05"},
{"certification":"","iso_3166_1":"BR","primary":false,"release_date":"2015-11-05"},
{"certification":"","iso_3166_1":"SE","primary":false,"release_date":"2015-11-04"},
{"certification":"","iso_3166_1":"IE","primary":false,"release_date":"2015-10-26"},
How would I go about saving the release date for the NL release?
You just need to iterate through the countries array, and check if the country code matches the one you wish to retrieve. For your example with 'NL':
var releaseNL;
for (var i = 0; i < $scope.movieList.releases.countries.length; i++) {
var release = $scope.movieList.releases.countries[i];
if (release['iso_3166_1'] == 'NL') {
releaseNL = release;
}
}
This is just one of many ways to do this (e.g. you could use angular.forEach, wrap it inside a function, etc.), but this should give you an idea.
Remark: I noticed you have been asking a lot of very basic questions today, which you could easily answer yourself with a bit more research. E.g. this question is not even AngularJS related, but just a simple JavaScript task. So maybe try to show a bit more initiative next time! ;)

json each parser ajax

I receive json information as:
{"entInfos":[{"conent":"entreprise","conadd":"45 rue de Paris","conadd2":"75010 \/ Paris| France"}]}
I need to extract each item for entInfos conent = entreprise, conadd = 45 ... etc ...
I tried, but isn't working.
Below is what I tried. Do, you have sample or idea ?
var json = JSON.parse(response);
$.each(json, function(i, item) {
alert(item.conadd);
alert(i.conadd);
});
you probably forgot about entInfos object:
var json = JSON.parse(response);
json.entInfos.forEach(function(info) {
alert(info.conadd);
alert(info.conadd2);
alert(info.conent);
});
And instead of jQuery's $.each method, I've just plain JavaScript's (ES5) forEach method.
Does this help?
Auto response :
var json = JSON.parse(response);
$(json.entInfos).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" ===== "+ v);
});
});