magento 2 custom api return in json without response tag Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30 pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?How to return a JSON object with a custom REST API in Magento 2?Force JSON Encode to Return ObjectMagento 2: Intercept controller's JSON responseHow do I get a response from REST API in JSON format in Magento 2?Magento 2 API - declare @return JSONMagento 2 - How to return custom json response from APIREST API vs JSONCustom REST API returns duplicate “response” tagHow to find Magento version using API (JSON specifically)Refresh Cache via JSON APIMagento 2: Is there a way to return custom json response from REST API without building a data interface?

Is there a way to fake a method response using Mock or Stubs?

Arriving in Atlanta (after US Preclearance in Dublin). Will I go through TSA security in Atlanta to transfer to a connecting flight?

How would it unbalance gameplay to rule that Weapon Master allows for picking a fighting style?

How to begin with a paragraph in latex

How did Elite on the NES work?

Why doesn't the university give past final exams' answers?

How long can a nation maintain a technological edge over the rest of the world?

Bright yellow or light yellow?

Why aren't road bicycle wheels tiny?

Variable does not exist: sObjectType (Task.sObjectType)

Why isn't everyone flabbergasted about Bran's "gift"?

Is it appropriate to mention a relatable company blog post when you're asked about the company?

Feather, the Redeemed and Dire Fleet Daredevil

How to compute a Jacobian using polar coordinates?

What is the purpose of the side handle on a hand ("eggbeater") drill?

What's called a person who work as someone who puts products on shelves in stores?

Specify the range of GridLines

Determinant of a matrix with 2 equal rows

What were wait-states, and why was it only an issue for PCs?

Like totally amazing interchangeable sister outfit accessory swapping or whatever

What to do with someone that cheated their way though university and a PhD program?

What does こした mean?

What does the black goddess statue do and what is it?

What's the difference between using dependency injection with a container and using a service locator?



magento 2 custom api return in json without response tag



Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30 pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?How to return a JSON object with a custom REST API in Magento 2?Force JSON Encode to Return ObjectMagento 2: Intercept controller's JSON responseHow do I get a response from REST API in JSON format in Magento 2?Magento 2 API - declare @return JSONMagento 2 - How to return custom json response from APIREST API vs JSONCustom REST API returns duplicate “response” tagHow to find Magento version using API (JSON specifically)Refresh Cache via JSON APIMagento 2: Is there a way to return custom json response from REST API without building a data interface?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have created a custom api following "inchoo" tutorial. But I am getting the data in string format instead of json.



From my browser I am getting a tag surrounding the api return as below.
enter image description here
But Chrome's postman extension showing a double quote ("") and some extra slashes () in the in the response even after header to "Accept":"application/json" and "Content-Type":"application/json".
enter image description here
I just want to receive the exact same string I am returning in my Model class.



 public function name() 
//return "Hello, raihanruhin";
$arr = '["name":"MasterCard","name":"VISA", "name":"DBBL-NEXUS", "name":"American Express"]';
return $arr;










share|improve this question














bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • Where is the Inchoo tutorial?

    – Khoa TruongDinh
    May 17 '17 at 7:49











  • inchoo.net/magento/api-magento/magento-2-custom-api I couldn't add this link in the original post because I have added two image already. 2+ isn't allowed with <10 points

    – Raihan Ruhin
    May 17 '17 at 7:54


















1















I have created a custom api following "inchoo" tutorial. But I am getting the data in string format instead of json.



From my browser I am getting a tag surrounding the api return as below.
enter image description here
But Chrome's postman extension showing a double quote ("") and some extra slashes () in the in the response even after header to "Accept":"application/json" and "Content-Type":"application/json".
enter image description here
I just want to receive the exact same string I am returning in my Model class.



 public function name() 
//return "Hello, raihanruhin";
$arr = '["name":"MasterCard","name":"VISA", "name":"DBBL-NEXUS", "name":"American Express"]';
return $arr;










share|improve this question














bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • Where is the Inchoo tutorial?

    – Khoa TruongDinh
    May 17 '17 at 7:49











  • inchoo.net/magento/api-magento/magento-2-custom-api I couldn't add this link in the original post because I have added two image already. 2+ isn't allowed with <10 points

    – Raihan Ruhin
    May 17 '17 at 7:54














1












1








1


1






I have created a custom api following "inchoo" tutorial. But I am getting the data in string format instead of json.



From my browser I am getting a tag surrounding the api return as below.
enter image description here
But Chrome's postman extension showing a double quote ("") and some extra slashes () in the in the response even after header to "Accept":"application/json" and "Content-Type":"application/json".
enter image description here
I just want to receive the exact same string I am returning in my Model class.



 public function name() 
//return "Hello, raihanruhin";
$arr = '["name":"MasterCard","name":"VISA", "name":"DBBL-NEXUS", "name":"American Express"]';
return $arr;










share|improve this question














I have created a custom api following "inchoo" tutorial. But I am getting the data in string format instead of json.



From my browser I am getting a tag surrounding the api return as below.
enter image description here
But Chrome's postman extension showing a double quote ("") and some extra slashes () in the in the response even after header to "Accept":"application/json" and "Content-Type":"application/json".
enter image description here
I just want to receive the exact same string I am returning in my Model class.



 public function name() 
//return "Hello, raihanruhin";
$arr = '["name":"MasterCard","name":"VISA", "name":"DBBL-NEXUS", "name":"American Express"]';
return $arr;







magento2 api json






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked May 17 '17 at 7:39









Raihan RuhinRaihan Ruhin

63




63





bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • Where is the Inchoo tutorial?

    – Khoa TruongDinh
    May 17 '17 at 7:49











  • inchoo.net/magento/api-magento/magento-2-custom-api I couldn't add this link in the original post because I have added two image already. 2+ isn't allowed with <10 points

    – Raihan Ruhin
    May 17 '17 at 7:54


















  • Where is the Inchoo tutorial?

    – Khoa TruongDinh
    May 17 '17 at 7:49











  • inchoo.net/magento/api-magento/magento-2-custom-api I couldn't add this link in the original post because I have added two image already. 2+ isn't allowed with <10 points

    – Raihan Ruhin
    May 17 '17 at 7:54

















Where is the Inchoo tutorial?

– Khoa TruongDinh
May 17 '17 at 7:49





Where is the Inchoo tutorial?

– Khoa TruongDinh
May 17 '17 at 7:49













inchoo.net/magento/api-magento/magento-2-custom-api I couldn't add this link in the original post because I have added two image already. 2+ isn't allowed with <10 points

– Raihan Ruhin
May 17 '17 at 7:54






inchoo.net/magento/api-magento/magento-2-custom-api I couldn't add this link in the original post because I have added two image already. 2+ isn't allowed with <10 points

– Raihan Ruhin
May 17 '17 at 7:54











3 Answers
3






active

oldest

votes


















0














Look how Magento 2 handles api response..



class MagentoFrameworkWebapiServiceOutputProcessor {
...
public function convertValue($data, $type)

if (is_array($data))
$result = [];
$arrayElementType = substr($type, 0, -2);
foreach ($data as $datum)
if (is_object($datum))
$datum = $this->processDataObject(
$this->dataObjectProcessor->buildOutputDataArray($datum, $arrayElementType)
);

$result[] = $datum;

return $result;
elseif ...



Magento 2 accept array type to response.



$arr = [
['name' => 'MasterCard'],
['name' => 'VISA'],
['name' => 'DBBL-NEXUS'],
['name' => 'American Express'],
];
return $arr;


or just..



$arr = '["name":"MasterCard","name":"VISA", "name":"DBBL-NEXUS", "name":"American Express"]';
return json_decode($arr, true);





share|improve this answer






























    0














    As I noted in this answer: https://magento.stackexchange.com/a/229971/2392, once you have the response string, you can tell PHP to convert it to a JSON object using this snippet:



    $object = json_decode( $response, false, 512, JSON_FORCE_OBJECT);


    Where $response is the string from your API response.



    Remember that variables only ever exist in the memory of the program you are executing. HTTP is a transport protocol, not a program, so it can only be used to send scalar (simple) variable types (e.g. String, integer, boolean) not complex types (like objects).



    So before an object can be sent over HTTP, a string representation of it must be created. This process is called serialisation (or serialization in US English).






    share|improve this answer






























      -1














      Modify your return line to:



      return json_decode(json_encode($arr), true);





      share|improve this answer























      • That will return a PHP associative array, not a string, which is what the OP appears to want

        – ProcessEight
        Jun 18 '18 at 11:47











      • The previous answers ahead of mine also have return values of PHP associative arrays. Additionally, the Magento core code given above in the answer before mine shows an array return value. Perhaps a return value of an array is more desirable than a string. As I recall my struggles with Magento from a year ago, I had a similar problem to the OP and the solution I gave solved my problem. So even though I've not given the response the OP requested, it may be the answer he needs.

        – noctufaber
        Jun 19 '18 at 13:19











      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "479"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f174788%2fmagento-2-custom-api-return-in-json-without-response-tag%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      Look how Magento 2 handles api response..



      class MagentoFrameworkWebapiServiceOutputProcessor {
      ...
      public function convertValue($data, $type)

      if (is_array($data))
      $result = [];
      $arrayElementType = substr($type, 0, -2);
      foreach ($data as $datum)
      if (is_object($datum))
      $datum = $this->processDataObject(
      $this->dataObjectProcessor->buildOutputDataArray($datum, $arrayElementType)
      );

      $result[] = $datum;

      return $result;
      elseif ...



      Magento 2 accept array type to response.



      $arr = [
      ['name' => 'MasterCard'],
      ['name' => 'VISA'],
      ['name' => 'DBBL-NEXUS'],
      ['name' => 'American Express'],
      ];
      return $arr;


      or just..



      $arr = '["name":"MasterCard","name":"VISA", "name":"DBBL-NEXUS", "name":"American Express"]';
      return json_decode($arr, true);





      share|improve this answer



























        0














        Look how Magento 2 handles api response..



        class MagentoFrameworkWebapiServiceOutputProcessor {
        ...
        public function convertValue($data, $type)

        if (is_array($data))
        $result = [];
        $arrayElementType = substr($type, 0, -2);
        foreach ($data as $datum)
        if (is_object($datum))
        $datum = $this->processDataObject(
        $this->dataObjectProcessor->buildOutputDataArray($datum, $arrayElementType)
        );

        $result[] = $datum;

        return $result;
        elseif ...



        Magento 2 accept array type to response.



        $arr = [
        ['name' => 'MasterCard'],
        ['name' => 'VISA'],
        ['name' => 'DBBL-NEXUS'],
        ['name' => 'American Express'],
        ];
        return $arr;


        or just..



        $arr = '["name":"MasterCard","name":"VISA", "name":"DBBL-NEXUS", "name":"American Express"]';
        return json_decode($arr, true);





        share|improve this answer

























          0












          0








          0







          Look how Magento 2 handles api response..



          class MagentoFrameworkWebapiServiceOutputProcessor {
          ...
          public function convertValue($data, $type)

          if (is_array($data))
          $result = [];
          $arrayElementType = substr($type, 0, -2);
          foreach ($data as $datum)
          if (is_object($datum))
          $datum = $this->processDataObject(
          $this->dataObjectProcessor->buildOutputDataArray($datum, $arrayElementType)
          );

          $result[] = $datum;

          return $result;
          elseif ...



          Magento 2 accept array type to response.



          $arr = [
          ['name' => 'MasterCard'],
          ['name' => 'VISA'],
          ['name' => 'DBBL-NEXUS'],
          ['name' => 'American Express'],
          ];
          return $arr;


          or just..



          $arr = '["name":"MasterCard","name":"VISA", "name":"DBBL-NEXUS", "name":"American Express"]';
          return json_decode($arr, true);





          share|improve this answer













          Look how Magento 2 handles api response..



          class MagentoFrameworkWebapiServiceOutputProcessor {
          ...
          public function convertValue($data, $type)

          if (is_array($data))
          $result = [];
          $arrayElementType = substr($type, 0, -2);
          foreach ($data as $datum)
          if (is_object($datum))
          $datum = $this->processDataObject(
          $this->dataObjectProcessor->buildOutputDataArray($datum, $arrayElementType)
          );

          $result[] = $datum;

          return $result;
          elseif ...



          Magento 2 accept array type to response.



          $arr = [
          ['name' => 'MasterCard'],
          ['name' => 'VISA'],
          ['name' => 'DBBL-NEXUS'],
          ['name' => 'American Express'],
          ];
          return $arr;


          or just..



          $arr = '["name":"MasterCard","name":"VISA", "name":"DBBL-NEXUS", "name":"American Express"]';
          return json_decode($arr, true);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jun 8 '17 at 22:31









          Nicholas MillerNicholas Miller

          863313




          863313























              0














              As I noted in this answer: https://magento.stackexchange.com/a/229971/2392, once you have the response string, you can tell PHP to convert it to a JSON object using this snippet:



              $object = json_decode( $response, false, 512, JSON_FORCE_OBJECT);


              Where $response is the string from your API response.



              Remember that variables only ever exist in the memory of the program you are executing. HTTP is a transport protocol, not a program, so it can only be used to send scalar (simple) variable types (e.g. String, integer, boolean) not complex types (like objects).



              So before an object can be sent over HTTP, a string representation of it must be created. This process is called serialisation (or serialization in US English).






              share|improve this answer



























                0














                As I noted in this answer: https://magento.stackexchange.com/a/229971/2392, once you have the response string, you can tell PHP to convert it to a JSON object using this snippet:



                $object = json_decode( $response, false, 512, JSON_FORCE_OBJECT);


                Where $response is the string from your API response.



                Remember that variables only ever exist in the memory of the program you are executing. HTTP is a transport protocol, not a program, so it can only be used to send scalar (simple) variable types (e.g. String, integer, boolean) not complex types (like objects).



                So before an object can be sent over HTTP, a string representation of it must be created. This process is called serialisation (or serialization in US English).






                share|improve this answer

























                  0












                  0








                  0







                  As I noted in this answer: https://magento.stackexchange.com/a/229971/2392, once you have the response string, you can tell PHP to convert it to a JSON object using this snippet:



                  $object = json_decode( $response, false, 512, JSON_FORCE_OBJECT);


                  Where $response is the string from your API response.



                  Remember that variables only ever exist in the memory of the program you are executing. HTTP is a transport protocol, not a program, so it can only be used to send scalar (simple) variable types (e.g. String, integer, boolean) not complex types (like objects).



                  So before an object can be sent over HTTP, a string representation of it must be created. This process is called serialisation (or serialization in US English).






                  share|improve this answer













                  As I noted in this answer: https://magento.stackexchange.com/a/229971/2392, once you have the response string, you can tell PHP to convert it to a JSON object using this snippet:



                  $object = json_decode( $response, false, 512, JSON_FORCE_OBJECT);


                  Where $response is the string from your API response.



                  Remember that variables only ever exist in the memory of the program you are executing. HTTP is a transport protocol, not a program, so it can only be used to send scalar (simple) variable types (e.g. String, integer, boolean) not complex types (like objects).



                  So before an object can be sent over HTTP, a string representation of it must be created. This process is called serialisation (or serialization in US English).







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jun 18 '18 at 11:44









                  ProcessEightProcessEight

                  7121417




                  7121417





















                      -1














                      Modify your return line to:



                      return json_decode(json_encode($arr), true);





                      share|improve this answer























                      • That will return a PHP associative array, not a string, which is what the OP appears to want

                        – ProcessEight
                        Jun 18 '18 at 11:47











                      • The previous answers ahead of mine also have return values of PHP associative arrays. Additionally, the Magento core code given above in the answer before mine shows an array return value. Perhaps a return value of an array is more desirable than a string. As I recall my struggles with Magento from a year ago, I had a similar problem to the OP and the solution I gave solved my problem. So even though I've not given the response the OP requested, it may be the answer he needs.

                        – noctufaber
                        Jun 19 '18 at 13:19















                      -1














                      Modify your return line to:



                      return json_decode(json_encode($arr), true);





                      share|improve this answer























                      • That will return a PHP associative array, not a string, which is what the OP appears to want

                        – ProcessEight
                        Jun 18 '18 at 11:47











                      • The previous answers ahead of mine also have return values of PHP associative arrays. Additionally, the Magento core code given above in the answer before mine shows an array return value. Perhaps a return value of an array is more desirable than a string. As I recall my struggles with Magento from a year ago, I had a similar problem to the OP and the solution I gave solved my problem. So even though I've not given the response the OP requested, it may be the answer he needs.

                        – noctufaber
                        Jun 19 '18 at 13:19













                      -1












                      -1








                      -1







                      Modify your return line to:



                      return json_decode(json_encode($arr), true);





                      share|improve this answer













                      Modify your return line to:



                      return json_decode(json_encode($arr), true);






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jun 8 '17 at 19:58









                      noctufabernoctufaber

                      13




                      13












                      • That will return a PHP associative array, not a string, which is what the OP appears to want

                        – ProcessEight
                        Jun 18 '18 at 11:47











                      • The previous answers ahead of mine also have return values of PHP associative arrays. Additionally, the Magento core code given above in the answer before mine shows an array return value. Perhaps a return value of an array is more desirable than a string. As I recall my struggles with Magento from a year ago, I had a similar problem to the OP and the solution I gave solved my problem. So even though I've not given the response the OP requested, it may be the answer he needs.

                        – noctufaber
                        Jun 19 '18 at 13:19

















                      • That will return a PHP associative array, not a string, which is what the OP appears to want

                        – ProcessEight
                        Jun 18 '18 at 11:47











                      • The previous answers ahead of mine also have return values of PHP associative arrays. Additionally, the Magento core code given above in the answer before mine shows an array return value. Perhaps a return value of an array is more desirable than a string. As I recall my struggles with Magento from a year ago, I had a similar problem to the OP and the solution I gave solved my problem. So even though I've not given the response the OP requested, it may be the answer he needs.

                        – noctufaber
                        Jun 19 '18 at 13:19
















                      That will return a PHP associative array, not a string, which is what the OP appears to want

                      – ProcessEight
                      Jun 18 '18 at 11:47





                      That will return a PHP associative array, not a string, which is what the OP appears to want

                      – ProcessEight
                      Jun 18 '18 at 11:47













                      The previous answers ahead of mine also have return values of PHP associative arrays. Additionally, the Magento core code given above in the answer before mine shows an array return value. Perhaps a return value of an array is more desirable than a string. As I recall my struggles with Magento from a year ago, I had a similar problem to the OP and the solution I gave solved my problem. So even though I've not given the response the OP requested, it may be the answer he needs.

                      – noctufaber
                      Jun 19 '18 at 13:19





                      The previous answers ahead of mine also have return values of PHP associative arrays. Additionally, the Magento core code given above in the answer before mine shows an array return value. Perhaps a return value of an array is more desirable than a string. As I recall my struggles with Magento from a year ago, I had a similar problem to the OP and the solution I gave solved my problem. So even though I've not given the response the OP requested, it may be the answer he needs.

                      – noctufaber
                      Jun 19 '18 at 13:19

















                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Magento Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f174788%2fmagento-2-custom-api-return-in-json-without-response-tag%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Grendel Contents Story Scholarship Depictions Notes References Navigation menu10.1093/notesj/gjn112Berserkeree

                      Area configuration aggregation error after install Porto themeMagento 2.1 CE Installed but front/backend not loading/workingCSS not loading on page within Magento 2 pageCannot install module in Magento 2no commands defined in the “setup” namespace. in Magento2Magento 2: Static files are present but shows 404Why do i have to always run the commands to clean cache in Magento 2.1.8?Failure reason: 'Unable to unserialize value.'Error 500 after magento migrationIn production mode the site does not loadMagento 2 : Error 500 after installing

                      Middle Expansion Olielle Resaix Definition: Uttering songs of triumph shouting with joy triumphant exulting Sejunction Journal 붙다 달 고급 품목 외출 The stretch trades the screeching tin. Definition: The act of speaking with a drawl a drawl Cough Sand Definition: An uproar a quarrel a noisy outbreak Shake Iron Publicize Horse House Baby 사과 Resaix Flaggy Jelly Temporary Unequaled Puppet A drop in the bucket Shrew 성격 회원 성질 미팅 The burn frames the tacky quality. Materialistic The smoke reduces the way. Yammoe Nondescript Cheek 얼굴 배 약하다 날리다 타다 The illegal country shows the iron. Help Rule Drearien Smoke Teaching Meaty Wasp Abraham Lincoln Jaws 진심 수리하다 Size Cork Idea Convert Think Lark John Lennon 거울 청소 군 추천하다 아이스크림