angularJS not parsing array of strings - arrays

Okay, I've been bashing my head bloody on this one:
I have the following JSON coming back from the server:
{
"SendDate" : "2015-03-16T22:48:27.747",
"SendTo" : {
"ContactIds" : ["28a24538-cdfc-4453-920d-86f57d7eaf22"],
"GroupIds" : []
},
"Message" : "MEETING TIME!!!!!"
}
I have checked this with several REST clients - this IS what comes back.
I have AngularJS "getting" this with an $http.get() operation, but I get an undefined on the "ContactIds" value - so, what I see in the JS Console is:
SendDate : "2015-03-16T22:48:27.747"
SendTo:
ContactIds: Array[1]
0: undefined
length: 1
I have NO IDEA what can be causing this.
Any ideas?
UPDATE:
I have attached an interceptor and intercepted the response and the result is the same when I feed the data to the console - but when I use:
JSON.stringify(data)
I can see that the Data in the Array is THERE!
UPDATE 2:
Okay now this is driving me nuts. I have played with the interceptor and if I stringify the response and then use JSON.parse() - it works fine, but when I pass the response through, it comes out messed up again.
I traced it through angular's parsing process all the way to the "fromJson()" function. (code below:) It comes into the function as a string. (Now here's the Bizzarro part)
I altered the code like this:
function fromJson(json) {
var obj1 = JSON.parse(json);
console.log("Obj1:");
console.log(obj1);
//my altered angular code
var obj2 = isString(json) ? JSON.parse(json) : json;
console.log("Obj2:");
console.log(obj2);
// Pass to program...
return obj1;
//return obj2;
/* original angular code:
return isString(json)
? JSON.parse(json)
: json;
*/
}
If I run it and return obj1, the console logs obj1's ContactIds "0" index as "undefined" - but obj2 logs as "28a24538-cdfc-4453-920d-86f57d7eaf22".
"GREAT!", I'm thinking - so I return obj2, but now it logs undefined but obj1's "0" index is now the correct value. (WTH?)
So I reverse the code, just to see, and Return obj1 - and I'll be damned - obj2 returns "28a24538-cdfc-4453-920d-86f57d7eaf22" and obj1 is undefined. (It's like teasing a monkey.)
It HAS to be something later on in the pipeline that is doing it - OR - it may have something to do with the array being GUID strings - but I use GUID strings elsewhere with no problems.
It could also be another "angular process" that I'm unaware of that is causing this - angular is quite impressive.
Either way, I'm super-confused.
This is so stupid - I'm surprised that an array of strings is such a difficulty - and what's worse, it seems I'm the only one having this problem. (I researched this for six hours yesterday...)
Any other ideas, guys?

OH MY GOD I'M SO STUPID!!!
First I'd like to thank everyone for trying to help me.
The answer is this - there was no problem, that is, not with Angular or its parser.
The Problem is that the Console was logging transformed data, which had an error at MY controller. The data on MY end was not matching the data in the list that I had in my controller - (Database Error).
BOTTOM LINE:
If you have this error pop up, do NOT troubleshoot from the top-down - troubleshoot from the bottom-up.
Angular has many checks and balances - if you don't get "bleeding failures" throughout the program, chances are the error is in YOUR code.
Thank you everyone for your help.

Related

Jasmine - How to Write Test for Array with Named properties and Object

I ran into a strange situation today, thanks to Javascript. I have a Object that look something like this.
$scope.main = [{main : 1},service:true];
Now when I try to expect this inside the jasmine test case for equating the Objects :
expect($scope.main).toEqual([{main : 1},service:true]);
This gives me an error :
Unexpected Token.
Strangely, This is a valid object for Javascript. But Jasmine is not able to accept that.
Is there any way to test this?
Thanks in advance!
EDIT : Attaching a structure screenshot.
Update
I see now based on your screenshot that you are creating the main object in multiple steps. I've shortened it to the following:
var main = [{main: 1}];
main.service = true;
In dev-tools, you are seeing main as something that looks like this: [{main: 1}, service: true].
However, don't be mislead. Dev-tools is showing you a structure that is just meant to be informative. You can't actually create that structure in one line of javascript, because it is invalid. You have to create it in multiple steps, like you have.
This is why when you try to create it in your test in one line, you are getting an Unexpected Token. error. In your test, you have to create the expected object in a similar fashion to how you created your main object. For example:
var expected = [{main: 1}];
expected.service = true;
expect(main).toEqual(expected);

can't manipulate JSON obtained through multiple $http.get and $q

I am trying to merge two jsons into one but can't make it work. I manage to retrieve the data I need from both get, but I have troubles manipulating the jsons.
I planned on using two for loops but it doesn't work :
$scope.coursesJson = $http.get('https://api.myjson.com/bins/18zi3');
$scope.reviewsJson = $http.get('https://api.myjson.com/bins/52toz');
$q.all([$scope.coursesJson, $scope.reviewsJson]).then(function (values){
$scope.coursesJson = values[0];
$scope.reviewsJson = values[1];
for(i = 0;i<$scope.coursesJson.length;i++){
for(j = 0;j<$scope.reviewsJson.length;j++){
if($scope.coursesJson[i].name = $scope.reviewsJson[j].name){
$scope.coursesJson[i].reviews.push($scope.reviewsJson[j]);
}
}
}
console.log($scope.coursesJson);
});
Using the console, I can visualise the data but $scope.coursesJson.length is undefined and I don't understand why.
Maybe I don't understand $q well ?
EDIT :
Here is an example of the elements you could find in the coursesJson file I get() :
[{"code":"123 ","name":"Acteurs","courseContentGrade":null,"courseTeachingGrade":null,"courseAverage":null,"reviews":null},
{"code":"1234","name":"Advanced Excel","courseContentGrade":null,"courseTeachingGrade":null,"courseAverage":null,"reviews":null}]
And an example of the elements you could find in the reviewsJson file I get() :
[{"code":"123 ","name":"Acteurs","professor":"Lalala","contentReview":"C'est très réussi.","teachingReview":"charismatique","contentGrade":8,"teachingGrade":8,"average":8,"trimester":"T2","day":"Jeudi / Thursday","time":"9h-12h","round":"1er tour","bet":21,"year":"2014/2015","upvotes":"0","author":"Piranha","passed":null},
{"code":"123 ","name":"Acteurs","professor":"LAlalalala","contentReview":"Très intéressant !","teachingReview":"Disponible, claire.","contentGrade":8,"teachingGrade":8,"average":8,"trimester":"T2","day":"Jeudi / Thursday","time":"9h-12h","round":"1er tour","bet":25,"year":"2014/2015","upvotes":"0","author":"Piranha","passed":null}]
I would like to add the elements found in the reviewsJson to the reviews field of the elements of coursesJson. Could that be the problem ? I thought that using the push() method would create the array, but maybe I need to change all "reviews":null to "reviews":[] in coursesJson ?
I went to the url https://api.myjson.com/bins/ID1 and it's not an array, but an object. Instead of $scope.coursesJson.length I think you shouldbe doing $scope.coursesJson.tracks.length
I solved my issue really easyly and my question was actually pretty stupid.
What I tried to achieve didn't have its place on the front but on the backend.

Qooxdoo/JSON Array undefined value

I'm working in order to connect my client to my server (node.js). I use this code :
var storeEmployees = new qx.data.store.Json("Load/Infos");
qx.event.Registration.addListener(storeEmployees, "loaded", function(){
var model = this.getModel();
console.log(model.getRecords());
console.log(model.getTotal());
console.log(model.getStatus());
}, storeEmployees);
My server send this value :
{records: ["bonjour", "aurevoir"], total:2, status:"success"}
however the "console.log(model.getRecords())" write on the console :
Object[undefined, undefined]
Instead of
Object["bonjour","aurevoir"]
Values for "getTotal" and "getStatus" are good. The problem is only for the array (simple array and complexe array).
Any idea ?
Thanks in advance !
The store marshals the data to model objects. This means that you are dealing with qx.data.Array here which unfortunately can not be accessed vie brackets notation (e.g. Data[0]). But this is what the console does. For debugging and logging you can access the plain array with the .toArray() method which then will show the results.

Unable to translate bytes [...] at index ... from specified code page to Unicode when adding to index

I am using Newtonsoft.Json to create the JSON to update add items to an index, but I get the following error when I POST the request:
{"error":{"code":"","message":"The request is invalid.","innererror":{"message":"parameters : Unable to translate bytes [E3] at index 752 from specified code page to Unicode.\r\n","type":"","stacktrace":""}}}
I know the error occurs with some non letter characters in some of the strings in the data that I am serializing. The string data comes from SQL, so I'm guessing something is going on to do with encoding that I cannot figure out.
When I inspect the JSON string, and put it in manually construct a request with the same data in Fiddler it all works fine.
Does anyone have any idea what might be the problem, and how I can work around it?
I found my own solution after a bit more digging.
Adding "StringEscapeHandling.EscapeNonAscii" to the serialization options solves the problem:
jsonSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};

Restangular chaining not working

I'm trying to use Restangular to chain calls to one(), and haven't figured out why this isn't working:
my_data = Restangular.one('mydata', 12345).one('foo', 789).get().then (some_data) ->
$scope.data_numbers = some_data.data.numbers
This should generate a call to '/mydata/12345/foo/789' but the chaining doesn't work. Instead, I get the error "Undefined is not a function". When I set a breakpoint and look at the result of doing just:
my_data = Restangular.one('mydata', 12345)
I can see that singleOne is undefined:
my_data
> Object {id: 197330, singleOne: undefined, route: "revenue", getRestangularUrl: function, getRequestedUrl: function…}
That seems to be the problem, though that's a bit of a guess. According to the Restangular docs and my previous experience, all of this should work, so I'm puzzled. I'm sure I'm missing something obvious here. To keep from being blocked I'm using a temporary customGET() but that's not very nice, so... Any suggestions would be very much appreciated.

Resources