简体   繁体   English

如何从 php 字符串创建 JSON 对象?

[英]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.我有一个由 json 样式数据组成的大型 php 字符串,需要以某种方式将其转换为 json 对象。 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?我如何将下面的 $string 字符串转换为 json 对象? 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: json_decode()使用json_decode()

$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 . 没有 JSON 对象这样的东西

What you have is a JSON Text expressed as a PHP string literal.您拥有的是一个表示为 PHP 字符串文字的 JSON 文本。

If you want to parse it into a PHP object, then use json_decode($string) .如果要将其解析为 PHP 对象,请使用json_decode($string)

If you want to parse it into a JavaScript object, then you have to pass the string to JavaScript somehow.如果要将其解析为 JavaScript 对象,则必须以某种方式将字符串传递给 JavaScript。 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.这可能涉及将其打印到 HTTP 请求的响应中,将其传递给V8或其他一些技术,具体取决于您想用它实现什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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