您好,欢迎访问一九零五行业门户网

php怎么将非标准json转为数组

在 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 字符串的示例,希望对你有所帮助。
以上就是php怎么将非标准json转为数组的详细内容。
其它类似信息

推荐信息