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

How to convert non-standard json to array in php

PHPz
PHPzOriginal
2023-04-25 17:35:34456browse

在 PHP 中,我们经常处理 JSON 数据格式,而 JSON 数据格式非常的标准化和统一,但是在一些特殊的情况下,我们可能会遇到一些非标准的 JSON 字符串,从而导致无法使用内置的 json_decode() 函数对其进行解析。

针对这些非标准的 JSON 字符串,我们需要手动对其进行解析和处理,以便将其转换为 PHP 数组或对象。下面是一些非标准的 JSON 字符串以及如何进行转换的示例。

示例一

假设我们有以下非标准的 JSON 字符串:

{key1: "value1", key2: "value2"}

首先,我们需要将其转换为标准的 JSON 格式,即:

{"key1": "value1", "key2": "value2"}

然后,我们可以使用 json_decode() 函数将其转换为 PHP 数组:

$jsonString = '{"key1": "value1", "key2": "value2"}';

$array = json_decode($jsonString, true);

print_r($array);

输出结果为:

Array
(
    [key1] => value1
    [key2] => value2
)

示例二

假设我们有以下非标准的 JSON 字符串:

{["key1", "value1"], ["key2", "value2"]}

这个 JSON 字符串的格式不仅非标准,而且还是一个非常特殊的格式。在这种情况下,我们需要手动对其进行解析和处理。

以下是处理这种非标准 JSON 字符串的代码示例:

$jsonString = '{["key1", "value1"], ["key2", "value2"]}';

$array = preg_replace('/\[\"(.*?)\",\s?\"(.*?)\"\]/', '"$1":"$2"', $jsonString);

$array = trim($array, '{}');

$array = '{' . $array . '}';

$array = json_decode($array, true);

print_r($array);

输出结果为:

Array
(
    [key1] => value1
    [key2] => value2
)

在这里,我们使用了正则表达式 preg_replace() 函数将 JSON 字符串中的每个键值对都转换为标准的格式。然后,我们将字符串中的大括号去掉,并使用 json_decode() 函数将其转换为 PHP 数组。

示例三

假设我们有以下非标准的 JSON 字符串:

{
    "key1": {
        "subKey1": "subValue1",
        "subKey2",
        "subValue2"
    },
    "key2": ["value1", "value2"]
}

在这个 JSON 字符串中,有一个非标准的键值对: "subKey2", "subValue2"。由于这个键值对的值缺少了键名,json_decode() 函数无法对其进行解析。

以下是处理这种非标准 JSON 字符串的代码示例:

$jsonString = '{
    "key1": {
        "subKey1": "subValue1",
        "subKey2",
        "subValue2"
    },
    "key2": ["value1", "value2"]
}';

$jsonString = preg_replace('/(([a-z0-9_]+):)/i', '"$2":', $jsonString);

$array = json_decode($jsonString, true);

print_r($array);

输出结果为:

Array
(
    [key1] => Array
        (
            [subKey1] => subValue1
            [subKey2] => subValue2
        )

    [key2] => Array
        (
            [0] => value1
            [1] => value2
        )

)

在这里,我们使用正则表达式匹配非标准的键值对并对其进行修正,然后使用 json_decode() 函数将其转换为 PHP 数组。

总结:

使用 PHP 自带的 json_decode() 函数可以非常方便地将 JSON 字符串转换为 PHP 数组或对象,但是当我们遇到非标准的 JSON 字符串时,我们需要手动对其进行解析和处理。在这篇文章中,我分享了三个处理非标准 JSON 字符串的示例,希望对你有所帮助。

The above is the detailed content of How to convert non-standard 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