I want to return JSON from M2 via webapi
But M2 removes first-level keys
Why is it happens? Is it feature or bug? Can it be ignored?
Magento 2.3.2
In webapi.xml
<route url="/V1/testapi" method="GET">
<service class="VendorModuleTestApi" method="fetch"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
Class TestApi
<?php
namespace VendorModuleModel;
class TestApi
{
/**
* @return string
*/
public function fetch() {
return [
'level1_key1' => [
'level2_key1' => 'testvalue',
],
123 => 'test',
'level1_key2' => 2,
];
}
}
Expected result:
{
"123": "test",
"level1_key1": {
"level2_key1": "testvalue"
},
"level1_key2": 2
}
Actual result:
[
{
"level2_key1": "testvalue"
},
"test",
2
]
2
Answers
Please see this question, I think the answers given there will apply to your problem.
In case someone still cherching solution for that, to have json with associative key you have to return array of your associative array :
Then you will get something like that :