简体   繁体   中英

Php convert string into JSON or an Array

Can anyone please help me for converting the string into an Array or JSON as well? Please take look on the text sample below;

{
    "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": []
},

I have tried

preg_match_all("/\{([^\)]*)\},/", $stream[0], $aMatches);

But it doesn't return anything. I also have tried json_decode, json_encode but could not find any success on it.

Thanks

The goal is to turn it into appropriate JSON format so that you can use json_decode . Ill break it down in steps:

  1. remove all \\n characters:

     $string = str_replace('\\n', '', $string); 
  2. remove last comma

     $string = rtrim($string, ','); 
  3. add brackets

     $string = "[" . trim($string) . "]"; 
  4. turn it into PHP array:

     $json = json_decode($string, true); 

Result:

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM