I am able to parse JSON that returns simple data, with JSON.parse but I am having trouble with data that returns objects, dates, strings, etc..
var theData=JSON.parse(theData);
Something like this JSON.parse returns [Object] object back with no data at all (I can see the data is being successfully returned because it returns all the data as a string if I have JSON.parse turned off).
{
"AppName": "TheName",
"AppUrl": "https:\/\/app\/icons\/unknown.png",
"aGUID": "45c055d2-2edc-d4444"."DateCreated": "8\/23\/2012 11:04AM", {
"ID": "yser123",
Name ":" User "}
}
What is the best way to go about parsing this data in javascript(I am not able to use jquery)?
Note: I had wrote the JSON assume its valid
Here is the code I am using to retreive the data..
var xhReq = new XMLHttpRequest();
xhReq.open("POST", "ClientService.svc/REST/GetDetail", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
return serverResponse;
First and foremost, don't use synchronous XHR. Rewrite your JavaScript to be asynchronous.
function getDetail(cb) {
var xhReq = new XMLHttpRequest();
xhReq.open("POST", "ClientService.svc/REST/GetDetail", true);
xhReq.onreadystatechange = function() {
if (xhReq.readyState == 4) cb(xhReq.responseText);
}
xhReq.send(null);
}
// to call:
getDetail(function(data) {
JSON.parse(data);
}
Second, your problem is not that JSON is being parsed incorrectly. It's your debugging call to alert. When you pass the serverResponse object, alert coerces the object into a string by calling the object's toString method, which simply returns '[object Object]'.
Try console.log. Objects can be inspected in the console.
It actually sounds like this is working. If you call some thing like this:
alert(JSON.parse(serverResponse))
It will display [object Object] which is correct. If you call
alert(JSON.parse(serverResponse).appName)
You should see the appName. If you are not seeing "SyntaxError"s being thrown, JSON.parse() is working
Your JSON format is wrong and the data needs to be a string.
So, this will work (I broke the lines to improve readability):
var data = "{" +
" \"AppName\": \"TheName\", " +
" \"AppUrl\": \"https:\/\/app\/icons\/unknown.png\", " +
" \"aGUID\": \"45c055d2-2edc-d4444\", " +
" \"DateCreated\": \"8\/23\/2012 11:04AM\", " +
" \"foo\": { " +
" \"ID\": \"yser123\", " +
" \"Name\":\"User\"" +
" }" +
"}";
var obj = JSON.parse(data);
alert( obj.AppName );
Of course, if you use simple quotes as string delimiter, the code would be:
var data = '{' +
' "AppName": "TheName", ' +
' "AppUrl": "https:\/\/app\/icons\/unknown.png", ' +
' "aGUID": "45c055d2-2edc-d4444", ' +
' "DateCreated": "8\/23\/2012 11:04AM", ' +
' "foo": { ' +
' "ID": "yser123", ' +
' "Name":"User"' +
' }' +
'}';
This not works:
var data = "{" +
" 'AppName': 'TheName', " +
" 'AppUrl': 'https:\/\/app\/icons\/unknown.png', " +
" 'aGUID': '45c055d2-2edc-d4444', " +
" 'DateCreated': '8\/23\/2012 11:04AM', " +
" 'foo': { " +
" 'ID': 'yser123', " +
" 'Name': 'User'" +
" }" +
"}";
jsFiddle: http://jsfiddle.net/9pmdm/1/
Related
I'm building an app that will send an email with variables, but i only want to include certain things if a variable is true (checkbox)
So I think i need If statments inside the email.putExtra(Intent.EXTRA_TEXT,""); but I dont seem to figure out how. it would look something like this:
public void Email (){
Date today = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY HH.mm");
String Time = formatter.format(today);
Intent email = new Intent(Intent.ACTION_SENDTO);
email.setData(Uri.parse("mailto:"));
email.putExtra(Intent.EXTRA_SUBJECT, "Audit" );
email.putExtra(Intent.EXTRA_TEXT, Time + "\n" + "Audit Results:"
if (MainActivity2.Send_A)=true{
MainActivity2.Ok_A1 + "\n" + MainActivity2.EditText1 + "\n" + MainActivity2.POA1
}
);
I know the code is completly wrong, but is it possible to do something like this?
Build up the string, than set that string to your function call.
var extraText = Time + "\n" + "Audit Results: ";
if (MainActivity2.Send_A === true){
extraText += MainActivity2.Ok_A1 + "\n" + MainActivity2.EditText1 + "\n" + MainActivity2.POA1;
}
email.putExtra(Intent.EXTRA_TEXT, extraText);
I need to get field source from JSON but my solution not working !!
this is json:
"trailers":{
"quicktime":[],
"youtube":[{
"name":"BandeAnnonce",
"size":"HD",
"source":"RqEuaM9Fsrg",
"type":"Trailer"
}]
}
i try to get the source :var link_trailer = data.trailers[0].youtube[0].source;
but is not working for me !!
trailers is object, you don't need to use index.
var link_trailer = JSON.parse(data).trailers.youtube[0].source;
Try the following code
var text = '{' +
'"trailers": {' +
'"quicktime": [],' +
'"youtube": [{' +
'"name": "BandeAnnonce",' +
'"size": "HD",' +
'"source": "RqEuaM9Fsrg",' +
'"type": "Trailer"' +
'}]' +
'}' +
'}';
obj = JSON.parse(text);
var source = obj.trailers.youtube[0].source;
document.getElementById("demo").innerHTML ="Source field value is :"+source;
Here is the working jsfiddle:http://jsfiddle.net/NJMyD/5387/
Parse json into object first
var link_trailer = JSON.parse(data).trailers[0].youtube[0].source
I am calling a function with one parameter "modalXPTO.HtmlFieldPrefix" sucessfuly like this:
modalXPTO.AdditionalJavaScriptCallback = "myFunction('" + modalXPTO.HtmlFieldPrefix + "')";
However, I would like to send more than one parameter, and I would expect this should work:
modalXPTO.AdditionalJavaScriptCallback = "myFunction('" + "{parentContainer:" + modalXPTO.ModalDivId + ", htmlFieldPrefix:" + modalXPTO.HtmlFieldPrefix + "}" + "')";
But it doesn't. Can anyone tell me what I am missing?
Here is the myFuntion declaration:
function myFunction(arg){
alert(arg.htmlFieldPrefix);
alert(arg.parentContainer);
}
I've fixed it.
modalXPTO.AdditionalJavaScriptCallback = "myFunction(" + "{parentContainer:'" + modalXPTO.ModalDivId + "', htmlFieldPrefix:'" + modalXPTO.HtmlFieldPrefix + "'}" + ")";
It is because of the misplaced "'". I wanted to pass an object with two parameters, but because of these characters I was passing a string instead.
I am trying to eventually have my json data displayed in a label. However, when I console.log the json data, only the last two objects are displayed. When I pass the data to a label, only the last object is displayed. Thanks in advance for any help!
Here is my code:
var json =
{
"Question:": " What is my name? ",
"Answer:": " James ",
"Question:": " What is my age? ",
"Answer:": " 31 "
};
for (var key in json)
{
if (json.hasOwnProperty(key))
{
console.log(key + " = " + json[key]);
}
}
var label = Ti.UI.createLabel({
text: key + json[key]
});
win3.add(label);
Your issue has nothing to do with Titanium. In JavaScript dictionary you can't have two same keys with different values. To demonstrate where you made mistake, I'll rewrite your first lines:
var json = {};
json["Question:"] = " What is my name? ";
json["Answer:"] = " James ";
// We are fine untill now.
json["Question:"] = " What is my age? ";
json["Answer:"] = " 31 ";
// Here you overwrote values for keys "Question:" and "Answer:" which were set above.
To fix your problem, I'd change your json dictionary into array of dictionaries:
var i, key, label;
var json = [
{
"Question:": " What is my name? ",
"Answer:": " James ",
},
{
"Question:": " What is my age? ",
"Answer:": " 31 "
}
];
for (i in json) {
for (key in json[i]) {
label = Ti.UI.createLabel({
text: key + json[i][key]
});
win3.add(label);
}
}
your json object key is duplicated, javascript does not complain from this, it will just overwrite the first key value with the second value
I'm passing a server control name to a javascript function.
function SelectAllCheckboxes(chk, ctrlName) {
alert(ctrlName);
The alert returns "gridPublishers"...
So...
Why does this work:
$("#MainContent_GridPublishers_gridPublishers").hide();
But this doesn't :
$("#MainContent_GridPublishers_" + ctrlName).hide();
also...
alert($("#MainContent_GridPublishers_" + ctrlName).length);
returns "0"
alert('T' + ctrlName + "T");
returns "TgridPublishersT"
console.log("#MainContent_GridPublishers_" + ctrlName);
returns "#MainContent_GridPublishers_GridPublishers "