Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a JSON string to array, not object

I've got a PHP array and echo that into javascript with json encode, i need to do it this way because it's going to be very dynamic. This is the code it echo's:

{"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 cant use .length or a for loop.

Does someone know what im doing wrong here?

Thanks

like image 910
Chris Avatar asked Aug 17 '11 16:08

Chris


People also ask

Can we convert JSON string to array?

Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.

How do I parse a string in JSON?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

How do you parse an array in JSON?

Use the JSON. parse() method to pase a JSON array, e.g. JSON. parse(arr) . The method parses a JSON string and returns its JavaScript value or object equivalent.

How do you parse an array of strings?

Use the JSON. parse() Expression to Convert a String Into an Array. The JSON. parse() expression is used to parse the data received from the web server into the objects and arrays.


1 Answers

You're trying to treat an Object like an Array, and an Object is not an Array, it is an Object.

Any time you see {} in JSON, that means "What is contained within these hallowed brackets is a dynamic object". When you see [], that means "Behold! I am an Array" (there are notable exceptions to this one: jQuery does some special work with to make itself look like an array).

So, in order to iterate through an Object, you'll 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] );
like image 181
cwallenpoole Avatar answered Oct 03 '22 08:10

cwallenpoole