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'
}
7
  • string[] Have you try this? Dec 26 '19 at 14:08
  • @BirjitsinhZala - Yes I tried, it didn't worked. Dec 27 '19 at 4:24
  • hiii, have you checked my updated answere? 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. Dec 27 '19 at 5:38
  • I mean to say create new file interface AssociativeArrayItemInterface 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"}]
2
  • Or second option send in array: [{"a":"1","b":"2"}] Dec 26 '19 at 14:15
  • Your second option cannot work as the {} symbols can't be used.
    – Seb
    May 13 at 3: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.