Parsing a JSON string for an array, not an object

I have a PHP array and echo in javascript with json encode, I need to do it like this because it will be very dynamic. This is his echo code:

{"notempty":true} 

And I use this to convert it to javascript:

 var myarray = eval('(' + json + ')'); 

For some reason, it creates an object instead of an array, and for that reason I cannot use .length or the for loop.

Does anyone know what I'm doing wrong here?

thanks

+4
source share
4 answers

You are trying to treat Object as Array , and Object not Array , it is Object .

Whenever you see {} in JSON, it means that "what is contained in these sacred brackets is a dynamic object." When you see [] , it means: β€œHere! I am an Array” (there are notable exceptions to this: jQuery does some special work to make itself look like an array).

So, to iterate through Object , you will want to use for... in .

 // eval BAD unless you know your input has been sanitized!. var myObj = JSON.parse('{"notempty":true}'); // personally, I use it in for... in loops. It clarifies that this is a string // you may want to use hasOwnProperty here as sometimes other "keys" are inserted for( var it in myObj ) console.log( "myObj["+it+"] = " + myObj[it] ); 
+4
source

{} is an object that contains one attribute named notempty . If you need an array, it should be

 [{"notempty":true}] 

which is an array with one element at index 0, which is an object with a single "notempty" attribute;

+1
source

By default, if you use member encoding in php, it will become a js object when decoding. To make it an array, you need to make an array in php:

PHP:

 $arr = "['notempty','notempty2','notempty3']"; 

Otherwise, you should convert it to an array in JS, but this seems like a waste, since switching through an object in javascript is much simpler:

Javascript:

 var arr = new Array(); for(var i in obj) arr[i] = obj[i]; 
+1
source

You can use jQuery to parse this array as follows:

 var p = []; $.each(jsonData, function (key, val) { p.push([val.propertyOne, val.propertyTwo]); }); 

I assume, of course, that you want to parse JSON, not an array or any other string.

0
source

All Articles