json在php中本身并没有很大作用,php主要提供 了两个函数来处理和转换,json_encode和json_decode,
json_encode
$arr = array(
'name' => '陈毅鑫', 'nick' => '深空', 'contact' => array( 'email' => 'shenkong at qq dot com', 'website' => 'http://www.', ) ); $json_string = json_encode($arr); echo $json_string; 以上数组将被转成字符串 {"name":"\u9648\u6bc5\u946b","nick":"\u6df1\u7a7a","contact":{"email":"shenkong at qq dot com","website":"http:\/\/www."}},值得注意的是 在非UTF-8编码下,中文字符将不可被encode,结果会出来空值,所以,如果你使用 gb2312编写PHP代码,那么就需要将包含中文的内容使用iconv或者mb转为UTF-8再进行json_encode,
以上字符串用json_decode 解码后会得到一个对象
$obj=json_decode($json_string); 我们可以通过访问对象的方式访问其中的属性
当然我们也可以使用 $obj=(array)(json_decode($arr));这种方式直接将其转为数组形式
还有一个问题,json_encode 如果编码中有中文字符,即使,我们用的是utf8的格式,但js又如何来调用其中的数据了? 这里外面将用到另外一个函数,urlencode。我们在使用json_encode之前,要编码的数据全部用urlencode函数处理一遍,在使用json_encode函数,再用 urldecode函数处理得到的json字符串,这样外面得到的既是json数据,中文也不会出现乱码。在这里,我提供一个自定义的函数,它也能达到我们的目的。 function customJsonEncode($a = false) { if (is_null($a)) return 'null'; if ($a === false) return 'false'; if ($a === true) return 'true'; if (is_scalar($a)) { if (is_float($a)) { // Always use "." for floats. return floatval(str_replace(",", ".", strval($a))); } if (is_string($a)) { static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')); return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"'; } else { return $a; } } $isList = true; for ($i = 0, reset($a); $i < count($a); $i++, next($a)) { if (key($a) !== $i) { $isList = false; break; } } $result = array(); if ($isList) { foreach ($a as $v) $result[] = customJsonEncode($v); return '[' . join(',', $result) . ']'; } else { foreach ($a as $k => $v) $result[] = customJsonEncode($k).':'.customJsonEncode($v); return '{' . join(',', $result) . '}'; } } json之所以用的广泛,在与其和js良好的支持。
在js中得到json的字符串数据,可以使用两个方法对其进行操作
var obj = eval('(' + str + ')');
var obj = str.parseJSON();
返回的将是js中的对象,然后对对象中的数据进行处理
|
|