[ Cant retrieve the JSON using Ajax ]
My JSON:
{
"operatorname": "LUKUP",
"Schedule": {
"channel": [
{
"bouquet": "Music",
"channelgenre": "English Music",
"prepaid_price": 15
},
{
"bouquet": "News",
"channelgenre": "English News",
"prepaid_price": 7
}
]
}
}
Ajax call:
$.ajax({
type: "POST",
url: my_url,
async: false,
success: function(result){
alert(JSON.stringify(result));
message= JSON.parse(result);
alert(message.Schedule.channel.length);
}
});
My json is coming. First alert message is giving my JSON. When i parse that json, error is coming like
Uncaught SyntaxError: Unexpected token o
Location: jquery.min.js.2
I tried solving this issue. Couldnt able to figure out where it is going wrong.
Can anyone help me
Answer 1
Remove the comas after "prepaid_price": 15
and "prepaid_price": 7
. You are also missing a closing }
at the end of your JSON.
You can validate your JSON here: http://www.jsoneditoronline.org/
{
"operatorname": "LUKUP",
"Schedule": {
"channel": [
{
"bouquet": "Music",
"channelgenre": "English Music",
"prepaid_price": 15
},
{
"bouquet": "News",
"channelgenre": "English News",
"prepaid_price": 7
}
]
}
}
Answer 2
You can use dataType: 'json',
in your AJAX-call, then your JSON will be parsed automatically and you don't need to call message = JSON.parse(result);
because your result will be already an Object.
Then you can call alert(result.Schedule.channel.length);
direct.
Your code would look like:
$.ajax({
type: "POST",
url: my_url,
async: false,
dataType: 'json',
success: function(result){
alert(result.Schedule.channel.length);
}
});