json each parser ajax - json

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);
});
});

Related

wordpress JSON API Uncaught SyntaxError: Unexpected token <script

I am using the wordpress JSON API to make an android app with angularJS. I am using the following code, and everything works fine.
$http.jsonp(WORDPRESS_API_URL + 'get_post/' +
'?post_id='+ postId +
'&callback=JSON_CALLBACK')
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
But in some pages of my wp site I use the jplayer module, which places this code at the <head>
<script>
var MP3jPLAYLISTS = [];
var MP3jPLAYERS = [];
</script>
This <script> tag comes along with the JSON return like this
<script>
var MP3jPLAYLISTS = [];
var MP3jPLAYERS = [];
</script>
angular.callbacks._2({"status":"ok","post": ....
which gives the Unexpected token
Any help is much appreciated!
You must build JSON API which will provide only JSON.
You have words JSON API in your question. API, answers of your API, must be JSON-valid. That means, that responses can only have headers and JSON data:
{"data": {"items": [1, 2, 3]}}
This is correct JSON.
In your case, response contains some HTML tags. It is not valid json, so your JSON request fails.
I found a solution, not so elegant but it works. I am writting it here just in case someone has the same problem.
The problem arises by the jplayer module. So in main.php file of this module you can make the following change:
function defineJSvars ()
{
if ( ! $this->JSvars ) {
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$pos = strpos($actual_link, "api/get_");
if ($pos == ""){
echo "\n<script>";
echo "\nvar MP3jPLAYLISTS = [];";
echo "\nvar MP3jPLAYERS = [];";
echo "\n</script>\n";
}
$this->JSvars = true;
}
}

AngularJS dynamic scope variables

I have a scope variable jsonData as below:
$scope.jsonData={id:'1234',abcd:{array:[{a:'data',b:'bdata',c:'cdata'},{a2:'a2data',b2:'b2data',c2:'c2data'}]},efg:{test:'testdata'}}
in my HTML I have a function calladd('jsonData.abcd.array') with a string
in my js file I want to add an JSON object to arrayinside the abcd JSON object
$scope.add(data) {
$scope[data].push({a3:'a3data',b3:'b3data',c3:'c3data'});
}
but I am unable to push data into array.
If you wanted to get ID, you can do
var id = $scope.jsonData.id;
//id = "1234"
You can use the same logic to add or get values
Calling myobject['prop1.prop2.whatever'] just doesn't work.
What you need is a recursive parser like :
$scope.add = function(data, scope){
scope = (typeof scope === "undefined") ? $scope : scope;
var datas = data.split('.');
if(datas.length == 1){
scope[datas[0]].push({
a3: 'a3data',
b3: 'b3data',
c3: 'c3data'
});
}else{
var first = datas.splice(0,1);
$scope.add(datas.join('.'), scope[first]);
}
};
And the fiddle

JSON Parsing in Titanium App (Multidimensional array)

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"]);

Reading JSON encoded Array form cakePHP view controller

Hello I have a JQuery/Ajax function as following:
$.ajax({
type : "POST",
url : "/posts/getids",
success: function(response){
console.log(response);
},
error: function() {
alert('An unexpected error has occurred! Please try later.');
}
});
In my cakePHP script I'm sending an array using the json_encode($array) function.
In firebug I get this result :
[{"Post":{"id":1}},{"Post":{"id":2}},{"Post":{"id":4}},{"Post":{"id":3}}]
So my question is How can I simply print only the ids like this : 1, 2, 3, 4
Thank you.
// Convert JSON to JavaScript array.
var dataFromServer = JSON.parse(response);
// Creating an array of id's.
var idArray = [];
// Moving data to "idArray".
for(i = 0; i < dataFromServer.length; i++){
idArray[i] = dataFromServer[i].Post.id;
}
// Checking the result.
console.log(idArray);
// [1, 2, 3, 4].

JSON.stringify gives me wrong json array

I have this code:
var sidebars = {};
var counter = 0;
// Loop through all already crated sidebars
$('.custom_dynamic_sidebars li').each(function(event) {
sidebars[counter] = $(this).text();
counter++;
});
var sidebars_string = JSON.stringify(sidebars);
but it gives me this string:
{\"0\":\"aa\",\"1\":\"bb\"}
Here is javascript which sends array to the server:
$.ajax({
url:"/welit_2/wp-admin/admin-ajax.php",
type:'POST',
data:'action=dynamic_sidebars&sidebars='+sidebars_string+'',
success:function(results) {
console.log(results);
}
});
does anyone know what am I doing wrong?
thx for your time
So I found a solution If you run stripslashes() on the JSON string before you output it, it works fine