Introduction to the application of JSON in PHP

  • 2020-05-24 05:17:02
  • OfStack

Starting with version 5.2, PHP natively provides the json_encode() and json_decode() functions, the former for encoding and the latter for decoding.
1. json_encode()
This function is mainly used to convert arrays and objects to json format. Let's look at an example of array conversion:
$arr = array (' a = > 1,'b'= > 2,'c'= > 3,'d'= > 4,'e'= > 5);
echo json_encode ($arr);
The results for
{" a ": 1," b ": 2," c ": 3," d ": 4," e ": 5}
Let's look at another example of object transformation:
 
  $obj->body = 'another post'; 
  $obj->id = 21; 
  $obj->approved = true; 
  $obj->favorite_count = 1; 
  $obj->status = NULL; 
  echo json_encode($obj); 

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

Since json only accepts utf-8 encoded characters, the parameter json_encode() must be utf-8 encoded, otherwise you get null characters or null. This is especially important when GB2312 is used in Chinese or ISO-8859-1 is used in foreign languages.

2. Indexed and associative arrays

PHP supports two arrays: an indexed array (indexed array) that holds only "values" (value), and an associative array (associative array) that holds only "name-value" pairs (name/value).
Since javascript does not support associative arrays, json_encode() only converts indexed arrays (indexed array) to array format and associative arrays (associative array) to object format.
For example, you now have an indexed array
 
  $arr = Array('one', 'two', 'three'); 
  echo json_encode($arr); 

The result is:
[" one two ", ""," three "]
If you change it to an associative array:
$arr = Array (' 1 '= > 'one', '2' = > 'two', '3' = > 'three');
echo json_encode ($arr);
The result changed:
{" 1 ", "one", "2" : "two", "3" : "three"}
Notice that the data format changed from "[]" (array) to "{}" (object).
If you need to force "indexed array" to "object", write this
json_encode ((object) $arr);
or
json_encode ($arr, JSON_FORCE_OBJECT);

3. Conversion of class (class)

Here is one PHP class:
 
  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; 
    } 
  } 

Now, convert an instance of this class to json:
 
  $foo = new Foo; 
  $foo_json = json_encode($foo); 
  echo $foo_json; 

The output is
{" public_ex ":" this is public "}
As you can see, everything (constants, private variables, methods, and so on) is missing except for the public variables (public).

4. json_decode()

This function is used to convert json text into the corresponding PHP data structure. Here's an example:
 
  $json = '{"foo": 12345}'; 
  $obj = json_decode($json); 
  print $obj->{'foo'}; // 12345 

Typically, json_decode() always returns an PHP object instead of an array. Such as:
= '{$json "a" : 1, "b" : 2, "c" : 3, "d" : 4, "e" : 5}';
$json var_dump (json_decode ());
The result is an PHP object:
 
  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 an PHP associative array, json_decode() needs to add a parameter true:
= '{$json "a" : 1, "b" : 2, "c" : 3, "d" : 4, "e" : 5}';
var_dump (json_decode ($json), true);
The result is an associative array:
 
  array(5) { 
     ["a"] => int(1) 
     ["b"] => int(2) 
     ["c"] => int(3) 
     ["d"] => int(4) 
     ["e"] => int(5) 
  } 


5. Common errors for json_decode()

The following three ways of writing json are all wrong. Can you see what is wrong?
 
  $bad_json = "{ 'bar': 'baz' }"; 
  $bad_json = '{ bar: "baz" }'; 
  $bad_json = '{ "bar": "baz", }'; 

Executing json_decode() on all three strings will return null and report an error.
The first error is that the delimiter of json (delimiter) allows only double quotes, not single quotes. The second error is that the "first name" of the json name value pair (the part to the left of the colon) must be in double quotation marks in all cases. The third error is that the comma cannot be added after the last value (trailing comma).
In addition, json can only be used to represent objects (object) and arrays (array). If you use json_decode() for a string or value, null will be returned.
var_dump(json_decode("Hello World")); //null

Related articles: