Reputation: 20538
Titanium SDK version: 1.6.1
iPhone SDK version: 4.2
I get this response back from the API I am consuming and I want a popup to show up on each error. For example: Desc can't be blank. I am using JavaScript.
This is the output in JSON.
{"desc":"can't be blank","value_1":"can't be blank"}
I tried this but it outputs every character, one by one.
for (var thekey = 0; thekey < response.length; thekey++) {
alert(response[thekey]);
};
How can I output the errors?
Upvotes: 0
Views: 225
Reputation: 816232
You have to first parse JSON into a JavaScript object, using JSON.parse
:
response = JSON.parse(response);
The JSON
object might not be available in older browsers, you have to include json2.js
then.
You cannot use a normal for
loop to iterate over an object. You have to use for...in
:
for (var thekey in response) {
if(response.hasOwnProperty(thekey)) {
alert(response[thekey]);
}
}
The properties of the object are desc
and value_1
, you cannot access them with numerical keys.
Upvotes: 1
Reputation: 7110
If the response
is a string you'll need to decode it to an object before you can do anything with it. Right now you're just looping through a string and printing each character.
You'll also probably want to use
for (var key in responseObject) {
var value = responseObject[key];
}
since it will be an object and your keys aren't numeric.
Upvotes: 1