JS中json字符串和json对象之间的转换,PHP中json字符串和php数组之间的转换
JS中:
json格式字符串转json对象(strJSON代表json字符串)
var obj = eval(strJSON);
var obj = strJSON.parseJSON();
var obj = JSON.parse(strJSON);
var str = obj.toJSONString();
var str = JSON.stringify(obj)
运用时候需要除了eval()以外,其他的都需要引入json.js包,切记!!!
PHP中:
1、json_encode():
1.1、将php数组转换为json字符串
1、索引数组
$arr =
Array( "one" , "two" , "three" );
echo json_encode( $arr );
|
输出
1 |
[ "one" , "two" , "three" ]
|
2、关联数组:
1 2 3 |
$arr =
Array( "1" => "one" , "2" => "two" , "3" => "three" );
echo json_encode( $arr );
|
输出变为
1 |
{ "1" : "one" , "2" : "two" , "3" : "three" }
|
1.2、将php类转换为json字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Foo
{
const ERROR_CODE
= "404" ;
public $public_ex = "this
is public" ;
private $private_ex = "this
is private!" ;
protected $protected_ex = "this
should be protected" ;
public function getErrorCode()
{
return self::ERROR_CODE;
}
}
|
现在,对这个类的实例进行json转换:
1 2 3 4 5 |
$foo =
|