編碼的世界 / 優質文選 / 文明

JS中json字符串和json對象之間的轉換,PHP中json字符串和php數組之間的轉換


2021年10月25日
-   

JS中:json格式字符串轉json對象(strJSON代表json字符串) var obj = eval(strJSON); 
var obj = strJSON.parseJSON(); 
var obj = JSON.parse(strJSON); 
json對象轉json格式字符串(obj代表json對象)  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

熱門文章