PHP json_encode - JSON_FORCE_OBJECT 混合对象和数组输出

我有一个想要进行 JSON 编码的 PHP 数据结构。它可以包含多个空数组,其中一些需要编码为数组,一些需要编码为对象。

例如,假设我有这个数据结构:

$foo = array(
  "bar1" => array(), // Should be encoded as an object
  "bar2" => array() // Should be encoded as an array
);

我想把它编码成:

{
  "bar1": {},
  "bar2": []
}   

但是如果我使用 json_encode($foo, JSON_FORCE_OBJECT) 我会得到对象:

{
  "bar1": {},
  "bar2": {}
}

如果我使用 json_encode($foo) 我将得到数组:

{
  "bar1": [],
  "bar2": []
}

有什么方法可以对数据进行编码(或定义数组),以便获得混合数组和对象?

最佳答案

创建 bar1 作为 new stdClass() 对象。这将是 json_encode() 区分它的唯一方法。可以通过调用 new stdClass() 或使用 (object)array()

强制转换来完成
$foo = array(
  "bar1" => new stdClass(), // Should be encoded as an object
  "bar2" => array() // Should be encoded as an array
);

echo json_encode($foo);
// {"bar1":{}, "bar2":[]}

或者通过类型转换:

$foo = array(
  "bar1" => (object)array(), // Should be encoded as an object
  "bar2" => array() // Should be encoded as an array
);

echo json_encode($foo);
// {"bar1":{}, "bar2":[]}

https://stackoverflow.com/questions/11670575/

相关文章:

php - 如何防止 json_encode() 删除包含无效字符的字符串

javascript - 未捕获的类型错误 : Cannot read property 'owne

python - 如何在保留矩阵维度的同时序列化 numpy 数组?

c# - 使用 C# 调用 json

python - 如何在 Django REST 框架中返回自定义 JSON

java - 非空属性引用 transient 值 - transient 实例必须在当前操作之前保

python - 在 View 中强制应用程序/json MIME 类型(Flask)

python - 使用 Scrapy 抓取 JSON 响应

c# - JavaScriptSerializer 可以排除具有空值/默认值的属性吗?

json - 雅虎财经全币种报价 API 文档