1

Trying to save a php array of objects into a json file, but boolean properties are being saved in strings :

[
    {
        "title" : "My Page",
        "url"   : "mypage",
        "type"  : "content",
        "final" : "false" // supposed to be simply false
    }
]

why is it? ... is there a flag I could use or something? currently I am using JSON_PRETTY_PRINT|JSON_NUMERIC_CHECK

2
  • 3
    Testing as far back as PHP 5.4-PHP 7, your example array always encodes correctly. The type of final in your array must be a string. Commented Feb 19, 2017 at 21:47
  • 1
    Show us a var_dump of an object Commented Feb 19, 2017 at 21:48

1 Answer 1

2

I have a feeling that the conversion is working correctly, and that the value actually is a string. You can confirm with gettype($var).

Please note that URL-encoding only gives you string values. You could try switching to JSON.

To give PHP the ability to handle application/json, add this function, and then call it:

function convertJsonBody() {
     $methodsWithDataInBody = array(
          'POST',
          'PUT',
     );

     if (
          isset($_SERVER['CONTENT_TYPE'])
          && (strpos(strtolower($_SERVER['CONTENT_TYPE']), 'application/json') !== FALSE)
          && isset($_SERVER['REQUEST_METHOD'])
          && in_array($_SERVER['REQUEST_METHOD'], $methodsWithDataInBody)
     ) {
          $_POST = json_decode(file_get_contents('php://input'), TRUE);
          foreach($_POST as $key => $value) {
               $_REQUEST[$key] = $value;
          }
     }
} 
Sign up to request clarification or add additional context in comments.

10 Comments

you are right, it might be something in the way I am passing the data to the server. i'll try to change that
the data in header is being passed like so : data[1][final]:true - is there any further processing which is needed to be done on server upon receiving the data?
If you are using urlencoding, all the values will be strings. You will have to convert to boolean. Or you can switch to using JSON content type ("application/json").
PHP doesn't natively understand JSON. If you just want to get it done, you can try something like $_POST = json_decode(file_get_contents('php://input'), TRUE);
That gives PHP the ability to handle application/json (although it's quick and dirty -- could also check $_SERVER["REQUEST_METHOD"] and $_SERVER["CONTENT_TYPE"], and populate $_REQUEST).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.