Judson
Judson

Reputation: 2325

Json_decode wrongly thinks string of numbers is json

My scripts tests to see if an array element contains json. All works well until I get to the array element which contains a string composed of numbers (zip code). This is what happens:

$s = '70115';
if (json_decode($s)){  
    echo 'this is json';
} else {
    echo 'this is not json';
}
//result: 'this is json'   
//expected result: 'this is not json'

I tried explicitly casting $s as a string and encoding it UTF8, but no luck.

Any idea why this is happening?

Upvotes: 2

Views: 378

Answers (2)

Gumbo
Gumbo

Reputation: 655239

Actually, JSON text is defined to be either a serialized object or array:

A JSON text is a serialized object or array.

  JSON-text = object / array

However, json_decode does also decode any other valid JSON value.

Upvotes: 0

moonwave99
moonwave99

Reputation: 22817

It is valid JSON.

You may want to check if you got an object actually:

$s = '70115';

if (is_object(json_decode($s))){  
    echo 'this is json';
} else {
    echo 'this is not json';
}

Upvotes: 2

Related Questions