<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.111cn.net/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head><body>
<script>
var obj = "([{name:'think',gender:'male'},{name:'lee',gender:'female'}])";
var ss = eval(obj);
alert(ss.length);
alert(ss[0].name+","+ss[1].name);
</script>
</body>
</html>看一款 php数组生成json的类.
<?php
class json {
var $jsonarr = array();
var $json = "";
/*递归生成json*/
function jsonencode($jsonarr) {
$this->json = empty($this->json) ? "{" : $this->json;
foreach($jsonarr as $key => $var) {
if(is_array($var)) {
$this->json .= '"'.$this->jsonkey($key).'":{';
$this->json .= $this->jsonstr($var).',';
} else {
$this->json .= '"'.$this->jsonkey($key).'":"'.$this->jsonvar($var).'",';
}
}
$this->json = substr($this->json, 0, -1)."}";
}
/*过滤值中特殊字符*/
function jsonvar($var) {
$var = str_replace(array('"'), array('"'), $var);
return $var;
}
/*过滤键值中特殊字符*/
function jsonkey($key) {
$key = str_replace(array("'", ":", """), array("", "", ""), $key);
return $key;
}
}
//调用
$obj = new json;
$obj->jsonencode($arr);
echo $obj->json;
?>