简体   繁体   中英

How to create JSON object from php string?

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}
     ]
    }
    ]
  }
  ]
}
";

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) {
        ...
      }
    }
  }
}

There's no such thing as a JSON object .

What you have is a JSON Text expressed as a PHP string literal.

If you want to parse it into a PHP object, then use json_decode($string) .

If you want to parse it into a JavaScript object, then you have to pass the string to JavaScript somehow. That might involve printing it into the response to an HTTP request, passing it to V8 or some other technique depending on what exactly you want to achieve with it.

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