Php 将字符串转换为 JSON 或数组

Sae*_*zal 1 php arrays json

任何人都可以帮我将字符串转换为数组或 JSON 吗?请看下面的文本示例;

{
    "account_id": "dfdfdf",
    "email": "mail-noreply@google.com",
    "id": "dfdfdf",
    "name": "Gmail Team",
    "object": "contact",
    "phone_numbers": []
},
{
    "account_id": "dfdf",
    "email": "saaddfsdfsdsfsdf@gmail.com",
    "id": "dfdf",
    "name": "Ab",
    "object": "contact",
    "phone_numbers": []
},
{
    "account_id": "dfdf",
    "email": "abc@gmail.com",
    "id": "dfdfdf",
    "name": "xyz",
    "object": "contact",
    "phone_numbers": []
},
Run Code Online (Sandbox Code Playgroud)

我试过了

preg_match_all("/\{([^\)]*)\},/", $stream[0], $aMatches);
Run Code Online (Sandbox Code Playgroud)

但它不会返回任何东西。我也尝试过 json_decode, json_encode 但没有找到任何成功。

谢谢

Cod*_*die 6

目标是将其转换为适当的 JSON 格式,以便您可以使用json_decode. 生病分解它的步骤:

  1. 删除所有\n字符:

    $string = str_replace('\n', '', $string);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 删除最后一个逗号

    $string = rtrim($string, ',');
    
    Run Code Online (Sandbox Code Playgroud)
  3. 添加括号

    $string = "[" . trim($string) . "]";
    
    Run Code Online (Sandbox Code Playgroud)
  4. 将其转换为 PHP 数组:

    $json = json_decode($string, true);
    
    Run Code Online (Sandbox Code Playgroud)

结果:

$string = ''; //your string
$string = str_replace('\n', '', $string);
$string = rtrim($string, ',');
$string = "[" . trim($string) . "]";
$json = json_decode($string, true);
var_dump($json);
Run Code Online (Sandbox Code Playgroud)

输出:

array (size=3)
  0 => 
    array (size=6)
      'account_id' => string '43z95ujithllc32fn02u8ynef' (length=25)
      'email' => string 'mail-noreply@google.com' (length=23)
      'id' => string '955xl0q3h9qe0sc11so8cojo2' (length=25)
      'name' => string 'Gmail Team' (length=10)
      'object' => string 'contact' (length=7)
      'phone_numbers' => 
        array (size=0)
          empty
  1 => 
    array (size=6)
      'account_id' => string '43z95ujithllc32fn02u8ynef' (length=25)
      'email' => string 'test-email1@gmail.com' (length=21)
      'id' => string '3u4e6i9ka3e7ad4km90nip73u' (length=25)
      'name' => string 'Test Account 1' (length=14)
      'object' => string 'contact' (length=7)
      'phone_numbers' => 
        array (size=0)
          empty
  2 => 
    array (size=6)
      'account_id' => string '43z95ujithllc32fn02u8ynef' (length=25)
      'email' => string 'test-email@gmail.com' (length=20)
      'id' => string 'bt3lphmp0g14y82zelpcf0w0r' (length=25)
      'name' => string 'Test Account' (length=12)
      'object' => string 'contact' (length=7)
      'phone_numbers' => 
        array (size=0)
          empty
Run Code Online (Sandbox Code Playgroud)