Php convert string into JSON or an Array

14,058

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 '[email protected]' (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 '[email protected]' (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 '[email protected]' (length=20)
      'id' => string 'bt3lphmp0g14y82zelpcf0w0r' (length=25)
      'name' => string 'Test Account' (length=12)
      'object' => string 'contact' (length=7)
      'phone_numbers' => 
        array (size=0)
          empty
Share:
14,058
Saeed Afzal
Author by

Saeed Afzal

I have over 14 years of professional experience in Web Development in various leading technologies. Very well experienced in managing the team within the agile process and delivering the products that meet the business objective and compliance carefully. I am a tech lover person and carefully focus on software architecture, data modeling, security vulnerabilities, the best approach followed, long-term maintainability, performance tuning, and problem solving. I have been involved in the development of web applications, large web-based systems, rich internet applications, desktop applications that are being used by real users around the globe and are available online. I have worked and successfully delivered projects for leading companies like Book Toto Australia, HiDrive, Center for non-violence, Lane housing, Bendigo Plastic Surgery, Altitude Advice, Active Rehab, Countrywide Heaters, Countrywide Window Coverings, Miller's Fencing, Active Rehab to name a few. I have also contributed to a few books such as Sass and Compass Designers Cookbook, Mastering Bootstrap 4, Mastering jQuery Mobile, Cloud Development, and Deployment with Cloud bees. I owned multiple diplomas in Computer Science, Software Engineer I & II, OOP, Database, Project management, and certifications in various technologies. Specialties: PHP / ReactJS / NodeJS / i18n / Software Architecting / Data Modeling / ES6 / Type-Script / JSON / jQuery / AJAX / Laravel / Zend Framwork / CodeIgnator / Doctrine ORM / Drupal 7 / Drupal 8 / Drupal Gardens / WordPress / Tailwind CSS / Bootstrap / Zurb Foundation / HTML 5 / CSS / SASS / LESS / Python / MySQL / PostgreSQL / Java / Groovy / Git / Apache / Code Reviews / Code Refactoring and Performance Tuning.

Updated on August 02, 2022

Comments

  • Saeed Afzal
    Saeed Afzal almost 2 years

    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": "[email protected]",
        "id": "dfdfdf",
        "name": "Gmail Team",
        "object": "contact",
        "phone_numbers": []
    },
    {
        "account_id": "dfdf",
        "email": "[email protected]",
        "id": "dfdf",
        "name": "Ab",
        "object": "contact",
        "phone_numbers": []
    },
    {
        "account_id": "dfdf",
        "email": "[email protected]",
        "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

  • CodeGodie
    CodeGodie about 8 years
    then you are not providing all the string in your original post.
  • CodeGodie
    CodeGodie about 8 years
    how is your string formed? Where are you getting the string from?
  • Saeed Afzal
    Saeed Afzal about 8 years
    It is string response from a third party API Nylas. I am posting exactly what I am having. I want array where data between { and }, can be get as internal array
  • CodeGodie
    CodeGodie about 8 years
    I see that you updated your string but that is very different than your original string. Before you had \n characters... what happened to them?
  • CodeGodie
    CodeGodie about 8 years
    in that case, do the same as my answer, but dont follow step 1.