Recently, while developing an API interface for a short URL service, I read many articles about APIs. The technology I used most often was JSON. JSON, also known as JavaScript Object Notation, is a lightweight data exchange format. Since my API development language is PHP, I need to use the interaction between JSON and PHP during data processing, namely data conversion.

Below, I will mainly introduce two ways to convert between JSON and arrays.

json_encode()

Since JSON only accepts characters encoded in UTF-8, the parameter of json_encode() must be UTF-8 encoded; otherwise, an empty character or null will be returned. This should be given particular attention when Chinese uses GB2312 encoding!

Example One (Array)

<?php  
$array_a =array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);  
echo json_encode($array_a);  
?>

Output

{"a":1,"b":2,"c":3,"d":4,"e":5}

Example Two (Object)

<?php
$obj->body           = 'another post';  
$obj->id             = 21;  
$obj->approved       = true;  
$obj->favorite_count = 1;  
$obj->status         = NULL;  
echo json_encode($obj);
?>

Output

{
    "body":"another post",  
    "id":21,  
    "approved":true,  
    "favorite_count":1,  
    "status":null  
}

json_decode()

This function is used to convert JSON text into the corresponding PHP data structure. Under normal circumstances, json_decode() always returns a PHP object rather than an array.

Case Three

<?php
$json ='{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>

Output

object(stdClass)#1 (5) {
  ["a"] => int(1)
  ["b"] => int(2)
  ["c"] => int(3)
  ["d"] => int(4)
  ["e"] => int(5)
}

If you want to force the generation of a PHP associative array, you need to add a parameter true to json_decode().

Example Four

<?php
$json ='{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json,true));
?>

Output

array(5) {
   ["a"] => int(1)
   ["b"] => int(2)
   ["c"] => int(3)
   ["d"] => int(4)
   ["e"] => int(5)
}

In addition, JSON can only be used to represent objects and arrays. Using json_decode() on a string or numeric value will return null.