Laravel 5.6 how to preserve float and int values in json response?












2















Searching about 20 minutes and still can't find reliable answer how to simply configure json respone for float type.



$array = DB::select('SELECT name, balance FROM ... blah blah blah'); // balance is float

return response()->json([
'data' => $array
]);


It returns:



{"data":[
{"name":"bob","balance":"889.37700000000018"},
{"name":"john","balance":"705.77400000000011"}
]}


So, as you might guess I want to have float type in this json data for balance values:



{"data":[
{"name":"bob","balance":889.37700000000018},
{"name":"john","balance":705.77400000000011}
]}


I can use standard json_encode() function with JSON_PRESERVE_ZERO_FRACTION flag to solve this issue.



But how to do the same thing with response()->json() ?



I've tried this sample but it fails and error occurs:



return response()->json([
'data' => $array
],
Response::HTTP_OK,
,
JSON_PRESERVE_ZERO_FRACTION
);









share|improve this question

























  • "it fails and error occurs:"...what error exactly? According to the source code github.com/laravel/framework/blob/master/src/Illuminate/Http/… you appear to have used the correct options.

    – ADyson
    Nov 13 '18 at 9:19













  • @ADyson, sorry, I didn't capture an error. But it would be great if I could put just one flag for this purpose instead of all params in response()->json() function.

    – mr.boris
    Nov 13 '18 at 9:50











  • it if threw an error, you must be able to capture it. Otherwise what would be the purpose of throwing it? Check your logs, and/or enable PHP error reporting and then see what response you get to the request which called this script.

    – ADyson
    Nov 13 '18 at 9:52













  • If you can use Eloquent/Model for this, you have a solution to cast your serialized model attributes by specifying it's mapping in $casts array.

    – Farooq Khan
    Nov 13 '18 at 9:56






  • 1





    @mr.boris if you have a solution, please write it in the Answers section...keep your question as a question and put your answer separately. This is a question-and-answer site, not a discussion forum. Please stick to the format. Then people can vote your question and your answer separately, and it's clear what the accepted solution was for future readers. Thanks.

    – ADyson
    Nov 13 '18 at 10:17
















2















Searching about 20 minutes and still can't find reliable answer how to simply configure json respone for float type.



$array = DB::select('SELECT name, balance FROM ... blah blah blah'); // balance is float

return response()->json([
'data' => $array
]);


It returns:



{"data":[
{"name":"bob","balance":"889.37700000000018"},
{"name":"john","balance":"705.77400000000011"}
]}


So, as you might guess I want to have float type in this json data for balance values:



{"data":[
{"name":"bob","balance":889.37700000000018},
{"name":"john","balance":705.77400000000011}
]}


I can use standard json_encode() function with JSON_PRESERVE_ZERO_FRACTION flag to solve this issue.



But how to do the same thing with response()->json() ?



I've tried this sample but it fails and error occurs:



return response()->json([
'data' => $array
],
Response::HTTP_OK,
,
JSON_PRESERVE_ZERO_FRACTION
);









share|improve this question

























  • "it fails and error occurs:"...what error exactly? According to the source code github.com/laravel/framework/blob/master/src/Illuminate/Http/… you appear to have used the correct options.

    – ADyson
    Nov 13 '18 at 9:19













  • @ADyson, sorry, I didn't capture an error. But it would be great if I could put just one flag for this purpose instead of all params in response()->json() function.

    – mr.boris
    Nov 13 '18 at 9:50











  • it if threw an error, you must be able to capture it. Otherwise what would be the purpose of throwing it? Check your logs, and/or enable PHP error reporting and then see what response you get to the request which called this script.

    – ADyson
    Nov 13 '18 at 9:52













  • If you can use Eloquent/Model for this, you have a solution to cast your serialized model attributes by specifying it's mapping in $casts array.

    – Farooq Khan
    Nov 13 '18 at 9:56






  • 1





    @mr.boris if you have a solution, please write it in the Answers section...keep your question as a question and put your answer separately. This is a question-and-answer site, not a discussion forum. Please stick to the format. Then people can vote your question and your answer separately, and it's clear what the accepted solution was for future readers. Thanks.

    – ADyson
    Nov 13 '18 at 10:17














2












2








2








Searching about 20 minutes and still can't find reliable answer how to simply configure json respone for float type.



$array = DB::select('SELECT name, balance FROM ... blah blah blah'); // balance is float

return response()->json([
'data' => $array
]);


It returns:



{"data":[
{"name":"bob","balance":"889.37700000000018"},
{"name":"john","balance":"705.77400000000011"}
]}


So, as you might guess I want to have float type in this json data for balance values:



{"data":[
{"name":"bob","balance":889.37700000000018},
{"name":"john","balance":705.77400000000011}
]}


I can use standard json_encode() function with JSON_PRESERVE_ZERO_FRACTION flag to solve this issue.



But how to do the same thing with response()->json() ?



I've tried this sample but it fails and error occurs:



return response()->json([
'data' => $array
],
Response::HTTP_OK,
,
JSON_PRESERVE_ZERO_FRACTION
);









share|improve this question
















Searching about 20 minutes and still can't find reliable answer how to simply configure json respone for float type.



$array = DB::select('SELECT name, balance FROM ... blah blah blah'); // balance is float

return response()->json([
'data' => $array
]);


It returns:



{"data":[
{"name":"bob","balance":"889.37700000000018"},
{"name":"john","balance":"705.77400000000011"}
]}


So, as you might guess I want to have float type in this json data for balance values:



{"data":[
{"name":"bob","balance":889.37700000000018},
{"name":"john","balance":705.77400000000011}
]}


I can use standard json_encode() function with JSON_PRESERVE_ZERO_FRACTION flag to solve this issue.



But how to do the same thing with response()->json() ?



I've tried this sample but it fails and error occurs:



return response()->json([
'data' => $array
],
Response::HTTP_OK,
,
JSON_PRESERVE_ZERO_FRACTION
);






php json laravel






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 10:18







mr.boris

















asked Nov 13 '18 at 9:08









mr.borismr.boris

448519




448519













  • "it fails and error occurs:"...what error exactly? According to the source code github.com/laravel/framework/blob/master/src/Illuminate/Http/… you appear to have used the correct options.

    – ADyson
    Nov 13 '18 at 9:19













  • @ADyson, sorry, I didn't capture an error. But it would be great if I could put just one flag for this purpose instead of all params in response()->json() function.

    – mr.boris
    Nov 13 '18 at 9:50











  • it if threw an error, you must be able to capture it. Otherwise what would be the purpose of throwing it? Check your logs, and/or enable PHP error reporting and then see what response you get to the request which called this script.

    – ADyson
    Nov 13 '18 at 9:52













  • If you can use Eloquent/Model for this, you have a solution to cast your serialized model attributes by specifying it's mapping in $casts array.

    – Farooq Khan
    Nov 13 '18 at 9:56






  • 1





    @mr.boris if you have a solution, please write it in the Answers section...keep your question as a question and put your answer separately. This is a question-and-answer site, not a discussion forum. Please stick to the format. Then people can vote your question and your answer separately, and it's clear what the accepted solution was for future readers. Thanks.

    – ADyson
    Nov 13 '18 at 10:17



















  • "it fails and error occurs:"...what error exactly? According to the source code github.com/laravel/framework/blob/master/src/Illuminate/Http/… you appear to have used the correct options.

    – ADyson
    Nov 13 '18 at 9:19













  • @ADyson, sorry, I didn't capture an error. But it would be great if I could put just one flag for this purpose instead of all params in response()->json() function.

    – mr.boris
    Nov 13 '18 at 9:50











  • it if threw an error, you must be able to capture it. Otherwise what would be the purpose of throwing it? Check your logs, and/or enable PHP error reporting and then see what response you get to the request which called this script.

    – ADyson
    Nov 13 '18 at 9:52













  • If you can use Eloquent/Model for this, you have a solution to cast your serialized model attributes by specifying it's mapping in $casts array.

    – Farooq Khan
    Nov 13 '18 at 9:56






  • 1





    @mr.boris if you have a solution, please write it in the Answers section...keep your question as a question and put your answer separately. This is a question-and-answer site, not a discussion forum. Please stick to the format. Then people can vote your question and your answer separately, and it's clear what the accepted solution was for future readers. Thanks.

    – ADyson
    Nov 13 '18 at 10:17

















"it fails and error occurs:"...what error exactly? According to the source code github.com/laravel/framework/blob/master/src/Illuminate/Http/… you appear to have used the correct options.

– ADyson
Nov 13 '18 at 9:19







"it fails and error occurs:"...what error exactly? According to the source code github.com/laravel/framework/blob/master/src/Illuminate/Http/… you appear to have used the correct options.

– ADyson
Nov 13 '18 at 9:19















@ADyson, sorry, I didn't capture an error. But it would be great if I could put just one flag for this purpose instead of all params in response()->json() function.

– mr.boris
Nov 13 '18 at 9:50





@ADyson, sorry, I didn't capture an error. But it would be great if I could put just one flag for this purpose instead of all params in response()->json() function.

– mr.boris
Nov 13 '18 at 9:50













it if threw an error, you must be able to capture it. Otherwise what would be the purpose of throwing it? Check your logs, and/or enable PHP error reporting and then see what response you get to the request which called this script.

– ADyson
Nov 13 '18 at 9:52







it if threw an error, you must be able to capture it. Otherwise what would be the purpose of throwing it? Check your logs, and/or enable PHP error reporting and then see what response you get to the request which called this script.

– ADyson
Nov 13 '18 at 9:52















If you can use Eloquent/Model for this, you have a solution to cast your serialized model attributes by specifying it's mapping in $casts array.

– Farooq Khan
Nov 13 '18 at 9:56





If you can use Eloquent/Model for this, you have a solution to cast your serialized model attributes by specifying it's mapping in $casts array.

– Farooq Khan
Nov 13 '18 at 9:56




1




1





@mr.boris if you have a solution, please write it in the Answers section...keep your question as a question and put your answer separately. This is a question-and-answer site, not a discussion forum. Please stick to the format. Then people can vote your question and your answer separately, and it's clear what the accepted solution was for future readers. Thanks.

– ADyson
Nov 13 '18 at 10:17





@mr.boris if you have a solution, please write it in the Answers section...keep your question as a question and put your answer separately. This is a question-and-answer site, not a discussion forum. Please stick to the format. Then people can vote your question and your answer separately, and it's clear what the accepted solution was for future readers. Thanks.

– ADyson
Nov 13 '18 at 10:17












2 Answers
2






active

oldest

votes


















2














You can casts your model attributes by providing a mapping as



class UserModel {

// mention mapping to primitive data-types as [int, float, boolean, decimal, real, array, object]
protected $casts = array(
"is_admin" => "boolean",
"age" => "integer",
"salary" => "float",
"certificates" => "array"
);
}


Resulted serialized model JSON will be casted as per your mappings.



[
{
"is_admin": true,
"age": 30,
"salary": 100.12,
"cetificates":
}
]





share|improve this answer































    0














    I solved it by sorting query result and casting balance value to float in foreach loop.



    $array= ;

    foreach($result as $row) {
    array_push($array, [
    'name' => $row->name,
    'balance' => (float) $row->balance
    ]);
    }

    return response()->json([
    'data' => $array
    ]);





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      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: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      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%2fstackoverflow.com%2fquestions%2f53277393%2flaravel-5-6-how-to-preserve-float-and-int-values-in-json-response%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      You can casts your model attributes by providing a mapping as



      class UserModel {

      // mention mapping to primitive data-types as [int, float, boolean, decimal, real, array, object]
      protected $casts = array(
      "is_admin" => "boolean",
      "age" => "integer",
      "salary" => "float",
      "certificates" => "array"
      );
      }


      Resulted serialized model JSON will be casted as per your mappings.



      [
      {
      "is_admin": true,
      "age": 30,
      "salary": 100.12,
      "cetificates":
      }
      ]





      share|improve this answer




























        2














        You can casts your model attributes by providing a mapping as



        class UserModel {

        // mention mapping to primitive data-types as [int, float, boolean, decimal, real, array, object]
        protected $casts = array(
        "is_admin" => "boolean",
        "age" => "integer",
        "salary" => "float",
        "certificates" => "array"
        );
        }


        Resulted serialized model JSON will be casted as per your mappings.



        [
        {
        "is_admin": true,
        "age": 30,
        "salary": 100.12,
        "cetificates":
        }
        ]





        share|improve this answer


























          2












          2








          2







          You can casts your model attributes by providing a mapping as



          class UserModel {

          // mention mapping to primitive data-types as [int, float, boolean, decimal, real, array, object]
          protected $casts = array(
          "is_admin" => "boolean",
          "age" => "integer",
          "salary" => "float",
          "certificates" => "array"
          );
          }


          Resulted serialized model JSON will be casted as per your mappings.



          [
          {
          "is_admin": true,
          "age": 30,
          "salary": 100.12,
          "cetificates":
          }
          ]





          share|improve this answer













          You can casts your model attributes by providing a mapping as



          class UserModel {

          // mention mapping to primitive data-types as [int, float, boolean, decimal, real, array, object]
          protected $casts = array(
          "is_admin" => "boolean",
          "age" => "integer",
          "salary" => "float",
          "certificates" => "array"
          );
          }


          Resulted serialized model JSON will be casted as per your mappings.



          [
          {
          "is_admin": true,
          "age": 30,
          "salary": 100.12,
          "cetificates":
          }
          ]






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 13 '18 at 10:10









          Farooq KhanFarooq Khan

          1,47911429




          1,47911429

























              0














              I solved it by sorting query result and casting balance value to float in foreach loop.



              $array= ;

              foreach($result as $row) {
              array_push($array, [
              'name' => $row->name,
              'balance' => (float) $row->balance
              ]);
              }

              return response()->json([
              'data' => $array
              ]);





              share|improve this answer




























                0














                I solved it by sorting query result and casting balance value to float in foreach loop.



                $array= ;

                foreach($result as $row) {
                array_push($array, [
                'name' => $row->name,
                'balance' => (float) $row->balance
                ]);
                }

                return response()->json([
                'data' => $array
                ]);





                share|improve this answer


























                  0












                  0








                  0







                  I solved it by sorting query result and casting balance value to float in foreach loop.



                  $array= ;

                  foreach($result as $row) {
                  array_push($array, [
                  'name' => $row->name,
                  'balance' => (float) $row->balance
                  ]);
                  }

                  return response()->json([
                  'data' => $array
                  ]);





                  share|improve this answer













                  I solved it by sorting query result and casting balance value to float in foreach loop.



                  $array= ;

                  foreach($result as $row) {
                  array_push($array, [
                  'name' => $row->name,
                  'balance' => (float) $row->balance
                  ]);
                  }

                  return response()->json([
                  'data' => $array
                  ]);






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 13 '18 at 10:18









                  mr.borismr.boris

                  448519




                  448519






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • 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%2fstackoverflow.com%2fquestions%2f53277393%2flaravel-5-6-how-to-preserve-float-and-int-values-in-json-response%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

                      Florida Star v. B. J. F.

                      Danny Elfman

                      Lugert, Oklahoma