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
=
new
Foo;
$foo_json
= json_encode(
$foo
);
echo
$foo_json
;
|
输出结果是
1
|
{
"public_ex"
:
"this is public"
}
|
2、json_decode():
将json文本转换为相应的PHP数据结构
2.1、通常情况下,json_decode()总是返回一个PHP对象,而不是数组比如:
1
2
3
|
$json
=
'{"a":1,"b":2,"c":3,"d":4,"e":5}'
;
var_dump(json_decode(
$json
));
|
结果就是生成一个PHP对象:
1
2
3
4
5
6
7
8
9
10
|
object(stdClass)#1 (5) {
[
"a"
] => int(1)
[
"b"
] => int(2)
[
"c"
] => int(3)
[
"d"
] => int(4)
[
"e"
] => int(5)
}
|
2.2、如果想要强制生成PHP关联数组,json_decode()需要加一个参数true:
1
2
3
|
$json
=
'{"a":1,"b":2,"c":3,"d":4,"e":5}'
;
var_dump(json_decode(
$json
,true));
|
结果就生成了一个关联数组:
1
2
3
4
5
6
7
8
9
10
|
array
(5) {
[
"a"
] => int(1)
[
"b"
] => int(2)
[
"c"
] => int(3)
[
"d"
] => int(4)
[
"e"
] => int(5)
}
|
3、json_decode()的常见错误
下面三种json写法都是错的
1
2
3
4
5
|
$bad_json
=
"{ 'bar': 'baz' }"
;
$bad_json
=
'{ bar: "baz" }'
;
$bad_json
=
'{ "bar": "baz", }'
;
|
对这三个字符串执行json_decode()都将返回null,并且报错。
第一个的错误是,json的分隔符(delimiter)只允许使用双引号,不能使用单引号。
第二个的错误是,json名值对的"名"(冒号左边的部分),任何情况下都必须使用双引号。
第三个的错误是,最后一个值之后不能添加逗号(trailing comma)。
另外,json只能用来表示对象(object)和数组(array),如果对一个字符串或数值使用json_decode(),将会返回null。
1
|
var_dump(json_decode(
"Hello World"
));
//null
|