Mario M.
Mario M.

Reputation: 416

PHP newer version fails decoding json "version like" string (ex: "0.7.4"->"0.7")

Executing this code in PHP I expect the string "0.7.4" remaining as "0.7.4" https://3v4l.org/gX4vM

$value = "0.7.4";

if(!empty($value))
{
  $jsonValue = json_decode($value);
  if(!empty($jsonValue)) $value = $jsonValue;
}

print_r( $value,false);

And this is true for almost every PHP version but in my AWS with PHP 5.6.9, and in this php sandbox (5.6.4 ?), I'm getting 0.7 http://ideone.com/2uuoHw

In my code $value can be a deserializable string or a simple string ("['a','b']", "{'a':'10'}", "abc", "2500", etc.) and I expect the json to decode it properly. But I have no idea how to avoid this strange issue.

Any idea? Thanks

Upvotes: 1

Views: 94

Answers (3)

gen_Eric
gen_Eric

Reputation: 227310

As stated, 0.7.4 is not valid JSON (according to the JSON spec), but PHP's json_decode can decode scalar values, too.

PHP implements a superset of JSON as specified in the original » RFC 4627 - it will also encode and decode scalar types and NULL. RFC 4627 only supports these values when they are nested inside an array or an object.

From: http://php.net/json_decode

If you had $value ='"0.7.4"'; (7 characters), then json_decode() would decode this to the string 0.7.4. But since your value is 0.7.4 (5 characters, since it's missing the double quotes), it can't be decoded.

Your example at https://3v4l.org/gX4vM is failing to decode $value and just printing out its original value (see: https://3v4l.org/e3um2).

EDIT: For some weird reason, the example at http://ideone.com/2uuoHw is decoding 0.7.4 as the float 0.7. That shouldn't happen. You should only get 0.7 if you stated with $value = "0.7": (see: https://3v4l.org/H2W5M).

Upvotes: 1

Mr. Llama
Mr. Llama

Reputation: 20909

Two things:

  1. Don't check if the result is empty(), check if the result is NULL. json_decode returns NULL if the input could not be decoded.

  2. The input string 0.7.4 is invalid JSON. Period. It worked at one point in PHP, but it was a mistake that it worked at all. You should not depend on this behavior as it is incorrect.

The modified version of your code should probably look like:

$value = "0.7.4";

if( !empty($value) )
{
    $jsonValue = json_decode($value);
    if ( $jsonValue !== NULL ) {
        // Pick a value to return
        $value = $jsonValue->something;

    } else {
        // Do nothing, leave $value as is
    }
}

var_dump($value);

Upvotes: 1

Fluinc
Fluinc

Reputation: 491

0.7.4 is not valid JSON.
This is valid JSON {"data": "0.7.4"}
Learn more about JSON here json.org

JSON to Object:

$json = '{"data": "0.7.4"}';
$obj = json_decode($json);
var_dump($obj);

JSON to Array:

$json = '{"data": "0.7.4"}';
$array = json_decode($json, true);
var_dump($array);

Upvotes: 2

Related Questions