skip to Main Content

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


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

    Login or Signup to reply.
  2. 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 VendorModuleModel;
    
    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
        }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search