PHP Decode Python Json to PHP Array: A Completed Guide for Beginners

By | April 24, 2020

We can use python to encode a python object to json string and send it to a php server.

To use python to encode an object to json, here are some examples:

Python Convert List to Json to Share Data: A Beginner Guide

Serialize Python Object to String and Deserialize It to Object for Python Beginners

However, if php server has received the python json string. How to process it? In this tutorial, we will introduce you how to do with an example.

Preliminary

Suppose php server has received a json string encoded by python. The string is:

<?php
<?php
$data = '{
  "2": [
    "Lily",
    23,
    "female"
  ],
  "0": [
    "Tom",
    23,
    "male"
  ],
  "1": [
    "Kate",
    22,
    "female"
  ]
}';
?>

Then we can decode it using php.

Decode json using php

We can use json_decode() function to decode a json string. Here is an example:

<?php
$data_decode = json_decode($data);
print_r($data_decode);
?>

Run this code, you will get this result.

stdClass Object
(
    [2] => Array
        (
            [0] => Lily
            [1] => 23
            [2] => female
        )

    [0] => Array
        (
            [0] => Tom
            [1] => 23
            [2] => male
        )

    [1] => Array
        (
            [0] => Kate
            [1] => 22
            [2] => female
        )

)

You will find php will decode a json string to a php class object. Here $data_decode variable is a php class object, which is not a friendly to us. We want $data_decode to be a php array.

Decode json string to php array

We can use code below to decode a json string to a php array.

<?php
$data_decode = json_decode($data, true);
print_r($data_decode);
?>

Run this code, you will find:

Array
(
    [2] => Array
        (
            [0] => Lily
            [1] => 23
            [2] => female
        )

    [0] => Array
        (
            [0] => Tom
            [1] => 23
            [2] => male
        )

    [1] => Array
        (
            [0] => Kate
            [1] => 22
            [2] => female
        )

)

Here $data_decode is a php array.

Category: PHP

Leave a Reply