Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JSON object from php string?

Tags:

json

string

php

I have a large php string that consists of json style data and need to somehow convert this into a json object. My string looks like something below: (it is one BIG string). Syntax for the string isn't exactly what I attached below but it's just an example. How would I convert a string lik $string below into a json object? Thanx.

$string = "
{
 \"name\": \"flare\",
 \"children\": [
  {
   \"name\": \"analytics\",
   \"children\": [
    {
     \"name\": \"cluster\",
     \"children\": [
      {\"name\": \"AgglomerativeCluster\", \"size\": 3938},
      {\"name\": \"CommunityStructure\", \"size\": 3812},
      {\"name\": \"HierarchicalCluster\", \"size\": 6714},
      {\"name\": \"MergeEdge\", \"size\": 743}
     ]
    }
    ]
  }
  ]
}
";
like image 578
user1899872 Avatar asked Jun 26 '26 15:06

user1899872


1 Answers

Use json_decode() for this:

$obj = json_decode($string);
var_dump($obj);

Output:

class stdClass#1 (2) {
  public $name =>
  string(5) "flare"
  public $children =>
  array(1) {
    [0] =>
    class stdClass#2 (2) {
      public $name =>
      string(9) "analytics"
      public $children =>
      array(1) {
        ...
      }
    }
  }
}
like image 119
hek2mgl Avatar answered Jun 29 '26 04:06

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!