Home  >  Article  >  Backend Development  >  How to convert json to array in php

How to convert json to array in php

PHPz
PHPzOriginal
2023-04-27 09:01:051207browse

JSON (JavaScript Object Notation) is a lightweight data exchange format commonly used for data interaction between web applications. In PHP, we often need to convert JSON format data into arrays for processing. This article will introduce in detail how to convert JSON to an array in PHP.

1. PHP built-in function json_decode()

There is a built-in function json_decode() in PHP that can convert a JSON format string into a PHP array. The syntax of this function is as follows:

mixed json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] )

Among them, the parameter $json represents the JSON string to be decoded; the parameter $assoc defaults to FALSE, indicating that an object is returned instead of an array; the parameter $depth represents the maximum depth of decoding; The parameter $options represents decoding options.

The following is a simple example to convert a JSON string into an array:

<?php
// JSON字符串
$json = &#39;{"name":"Tom","age":18,"hobbies":["reading","writing","swimming"]}&#39;;

// 将JSON字符串转换为数组
$arr = json_decode($json, true);

// 输出数组
print_r($arr);
?>

The output result is:

Array (
    [name] => Tom
    [age] => 18
    [hobbies] => Array (
        [0] => reading
        [1] => writing
        [2] => swimming
    )
)

2. PHP handles JSON parsing errors

However, in actual development, sometimes we encounter JSON parsing errors, such as format errors, data type mismatches and other issues. At this time, we can handle it in the following two ways:

  1. Use try-catch to catch exceptions

You can use try-catch statements in PHP to catch exceptions and execute them. deal with. When the json_decode() function parses a JSON string, it will throw an exception if the format is incorrect or there are other errors. We can use try-catch to catch these exceptions and handle them.

<?php
// JSON字符串
$json = &#39;{"name":"Tom","age":18,"hobbies":}&#39;; // 格式错误

// 将JSON字符串转换为数组
try {
    $arr = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
    print_r($arr);
} catch (JsonException $e) {
    echo "JSON字符串格式错误:" . $e->getMessage();
}
?>

The output result is: JSON string format error: Syntax error

  1. Use the json_last_error() function to obtain error information

In addition to catching exceptions, You can also use the json_last_error() function to get error information when parsing a JSON string. This function returns an integer representing the error code of the last JSON parse. For example, when the format of the parsed JSON string is incorrect, the json_last_error() function will return JSON_ERROR_SYNTAX. We can judge whether the parsing is successful based on the error code and handle it accordingly.

The following is an example:

<?php
// JSON字符串
$json = &#39;{"name":"Tom","age":18,"hobbies":}&#39;; // 格式错误

// 将JSON字符串转换为数组
$arr = json_decode($json, true);

// 判断是否解析成功
if (json_last_error() == JSON_ERROR_NONE) {
    print_r($arr);
} else {
    echo "JSON字符串格式错误:" . json_last_error_msg();
}
?>

The output result is: JSON string format error: Syntax error

Summary

In PHP, we can use The built-in function json_decode() converts a JSON-formatted string into an array. If an error occurs when parsing a JSON string, we can use the try-catch statement to catch the exception or use the json_last_error() function to obtain the error information and process it according to different error codes. This article introduces two methods of handling errors, which can be chosen according to the actual situation.

The above is the detailed content of How to convert json to array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn