将具有另一个对象的多维对象转换为json

时间:2017-05-09 14:46:55

标签: php json

我有一个对象需要转换为json以与API进行交互,因此我必须维护对象和数组结构。请采取以下措施:

stdClass Object
(
[method] => something
[params] => Array
    (
        [instructions] => stdClass Object
            (
                [a] => 1
                [b] => 2
            )
    )
)

将其传递给json_encode(),但第二个对象instructions丢失,只是将其转换为另一个数组:

{ "method":"something",
  "params":{
    "instructions": { "a":1,"b":2 } 
  }
}

当我最终应该使用方括号时,如:

{ "method":"something",
  "params":{ 
    "instructions": [ { "a":1,"b":2 } ] 
  } 
}

我注意到有一个预定义的常量,比如JSON_FORCE_OBJECT,但是添加它作为json_encode的选项似乎有0效果。我错过了什么?

2 个答案:

答案 0 :(得分:1)

您对instructions的要求是一个对象数组(您使用的[ { } ]表达式),但您将其设置为只有两个字段的对象。请尝试以下方法:

$arr = (object)[
    'method' => 'something',
    'params' => [
        'instructions' => [
            [
                'a' => 1,
                'b' => 2
            ]
        ]
    ]
];
echo json_encode($arr);

输出:

{
    "method": "something",
    "params": {
        "instructions": [
            {
                "a": 1,
                "b": 2
            }
        ]
    }
}

答案 1 :(得分:0)

首先,json_encode工作正常:

$x = (object) [
  "method" => "something",
    "params" => [
      "instructions" => (object) [
        "a" => 1,
        "b" => 2
     ]
   ]
];

echo json_encode($x);

// {"method":"something","params":{"instructions":{"a":1,"b":2}}}

这不是有效的JSON

"instructions": [ "a":1,"b":2 ] 

javascript中没有关联数组这样的东西

根据您的评论和编辑,您想要将数组更改为

$x = (object) [
  "method" => "something",
    "params" => [
      "instructions" => [
        (object) [
          "a" => 1,
          "b" => 2
       ]
     ]
   ]
];