Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert javascript string to an array

I'm retrieving an array of objects from a hidden html input field. The string I'm getting is:

"{"id":"1234","name":"john smith","email":"[email protected]"},{"id":"4431","name":"marry doe","email":"[email protected]"}"

Now I need to pass this as an array of objects again. How do I convert this string into array of objects?

like image 225
dev.e.loper Avatar asked Apr 26 '10 00:04

dev.e.loper


People also ask

Is a JavaScript string an array?

A string is just a one-dimensional array — a vector — with elements of the type character. This means all sequence functions also work on strings. There is no special set of functions just for operating on strings (except those for string-specific operations).

What is array [- 1 in JavaScript?

As others said, In Javascript array[-1] is just a reference to a property of array named "-1" (like length ) that is usually undefined (because array['-1'] is not evaluated to any value).


2 Answers

var array_of_objects = eval("[" + my_string + "]");

This executes the string as code, which is why we need to add the [] to make it an object. This is also one of the few legitimate uses for eval as its the fastest and easiest way. :D

like image 85
Gordon Gustafson Avatar answered Sep 25 '22 14:09

Gordon Gustafson


Assuming that str holds valid JSON syntax, you can simply call eval(str).

For security reasons, it's better to use a JSON parser, like this:

JSON.parse(str);

Note that str must be wrapped in [] to be a valid JSON array.

like image 42
SLaks Avatar answered Sep 21 '22 14:09

SLaks