【问题标题】:php - combining json with json_decodephp - 将 json 与 json_decode 结合
【发布时间】:2009-11-10 06:37:36
【问题描述】:

我试图在 PHP 中将多个 JSON 对象组合成一个。我正在遍历 JSON 对象,对它们进行解码,解析出我想要保留的部分,并将它们存储在我的 php 类的一个属性中。

假设我的 json 对象格式如下:

{
    "lists" : {
        "list" : [
            {
                "termA" : 2 ,
                "termB" : "FOO" 
            } 
        ] 
    } 
}

我想最终像这样将所有内容组合成一个 JSON 对象。

{
    "lists" : {
        "list" : [
            {
                "termA" : 2 ,
                "termB" : "FOO" 
            },
            {
                "termA" : 2 ,
                "termB" : "FOO" 
            } 
        ] 
    } ,
    "lists" : {
        "list" : [
            {
                "termA" : 4 ,
                "termB" : "BAR" 
            },
            {
                "termA" : 4 ,
                "termB" : "BAR" 
            } 
        ] 
    } 
}

我正在尝试将数组存储在我的类中的一个属性中,该函数被称为 iteratrivley:

   private function parseData($json){
        $decodeData = json_decode($json);
            $list = $decodeData->lists;
        $this->output .= $list
    }

但是,我在“$this->output .= $list”行中收到以下错误。

stdClass 类的对象无法转换为字符串

现在 $this->output 没有初始值。临时存储“列表”数组,然后在遍历所有 json 对象后重新格式化它们的最佳方法可能是什么?

谢谢。

【问题讨论】:

    标签: php json


    【解决方案1】:

    你很亲密:

    private function parseData($json){
      $decodeData = json_decode($json);
      $list = $decodeData['lists'];
      $this->output .= $list
    }
    

    【讨论】:

      【解决方案2】:
      {
          "lists" : {
            ...
          } ,
          "lists" : {
            ...
          } 
      }
      

      这不是有效/有意义的 JSON。您有两次具有相同键 (lists) 的哈希。你会如何解决这个问题?

      【讨论】:

      • 因为jsonlint不够?限制不是语法,所以这可能就是原因。请参阅:rfc-4627,第 2.2 节的定义(或者考虑一下 - 这很直观)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      相关资源
      最近更新 更多