1

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="Vendor\Module\TestApi" method="fetch"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>

Class TestApi

<?php
namespace Vendor\Module\Model;

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
]
pavdan
  • 31
  • 1
  • 4

2 Answers2

0

Please see this question, I think the answers given there will apply to your problem.

jsims281
  • 2,206
  • 2
  • 30
  • 57
0

In case someone still cherching solution for that, to have json with associative key you have to return array of your associative array :

<?php
namespace Vendor\Module\Model;

class TestApi
{ 
   /**
     * @return string
     */
    public function fetch() {
        $result = [
            'level1_key1' => [
                'level2_key1' => 'testvalue',
            ],
            123 => 'test',
            'level1_key2' => 2,
        ];
        return [$result];
    }
}

Then you will get something like that :

[
    {
        "level1_key1": {
            "level2_key1": "testvalue"
        },
        "123": "test",
        "level1_key2": 2
    }
]
Océane
  • 21
  • 6
  • umm.. no ) Because it changes the data structure (being deeper for 1 level). Of course its useful trick, but still not the correct solution. Unfortunately, there's no solution 'from the box'. U have to change data structure (as shown in this answer, for example) or modify Magento core – pavdan May 04 '21 at 14:22