3

I need to send associative array in response. Keys can be dynamic like

{
 'a':'1',
 'b':'2'
}

I already tried mixed[], mixed, string, string[], array and array[]. But I always get following result.

{
 '1',
 '2'
}
  • string[] Have you try this? – Birjitsinh Zala Dec 26 '19 at 14:08
  • @BirjitsinhZala - Yes I tried, it didn't worked. – piyush_systematix Dec 27 '19 at 4:24
  • hiii, have you checked my updated answere? – Birjitsinh Zala Dec 27 '19 at 5:30
  • Hi, yes. First option is not working. Second option is working but it is adding escape character '\' in the response like "[{\"a\":\"1\",\"b\":\"2\"}]". Seems I will need to handle it client side. – piyush_systematix Dec 27 '19 at 5:38
  • I mean to say create new file interface AssociativeArrayItemInterface – Birjitsinh Zala Dec 27 '19 at 5:49
1

First create this interface in your app/code/Vendor/Module/Api/Data

/**
 * Interface which represents associative array item.
 */
interface AssociativeArrayItemInterface
{
    /**
     * Get key
     * 
     * @return string
     */
    public function getKey();

    /**
     * Get value
     * 
     * @return string
     */
    public function getValue();
}

Apply @return \Vendor\Module\Api\Data\AssociativeArrayItemInterface[] datatype for on comment

/**
    * @return \Vendor\Module\Api\Data\AssociativeArrayItemInterface[]
    **/
    public function getSettings();

    /**
    * @return \Vendor\Module\Api\Data\AssociativeArrayItemInterface[]
    **/
    public function getExtra();

SECOND OPTION: send data in below formate

[{"a":"1","b":"2"}]
| improve this answer | |
  • Or second option send in array: [{"a":"1","b":"2"}] – Birjitsinh Zala Dec 26 '19 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.