开发者

Convert javascript string to an array

开发者 https://www.devze.com 2022-12-28 16:35 出处:网络
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\":\"jsmith@bla开发者_运维问答h.com\"},{\"id\":\"4431

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":"jsmith@bla开发者_运维问答h.com"},{"id":"4431","name":"marry doe","email":"mdoe@blah.com"}"

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


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


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.


There are many bad formatted string object, GET from API, old code, etc. Bad format doesn't means it drops error in code, but drops error for input of JSON.parse().

// not " wrapped key syntax
var str = "{ a: 2 }";
console.log( JSON.parse( str ) );
//  SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data

// 'key', or 'value' syntax
var str = " { 'a': 2 } ";
console.log( JSON.parse( str ) );
// SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data

//syntax OK
var str = '{ "a": 2 }';
console.log( JSON.parse( str ) );
// Object { a: 2 }

There is a solution:

// Convert any-formatted object string to well formatted object string:
var str = "{'a':'1',b:20}";
console.log( eval( "JSON.stringify( " + str + ", 0, 1 )" ) );

/* 
"{
 "a": "1",
 "b": 20
}"
*/

// Convert any-formatted object string to object:
console.log( JSON.parse(  eval( "JSON.stringify( " + str + ", 0, 1 )" ) ) );
// Object { a: "1", b: 20 }


var str=eval([{'id':'1','txt':'name1'},{'id':'2','txt':'name2'},{'id':'3','txt':'name3'}])
for(var i=0;i<str.length;i++)
{
alert(str[i].txt);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号