0

This is my first post, I hope I'm doing everything OK asking my question: I want to create a function which detects whether a string is valid JSON or not. I already read good topic here (Fastest way to check if a string is JSON in PHP?) but I wanted to add the check functionality for the first character as this function will get lot of non-JSON input. Yet it keeps failing, I don't know why...

Here's the function I wrote so far:

function isJson($string){
    $string = trim($string);
    vardump($string);  //for debugging
    if($string[0]!='{'||$string[0]!='['){ //check for first char
      echo("{$string[0]}!={ OR {$string[0]}!=["); //this actually prints {!={ OR {!=[ every time it comes across valid JSON...
      return false;
    }
    if(json_decode($string)==true)return true;
    else return false;
    }

Could you help me with this please, as it is starting to drive me insane? Thank you in advance!

9
  • what does you vardump look like? ( and it should be var_dump($string)) Commented May 30, 2013 at 15:30
  • 1
    Not sure if you gain any speed by checking the first character yourself. I guess the "json_decode" is clever enough to stop parsing as soon as it detects that a json string is not correctly formatted. Wild guess , but you should benchmark it. Commented May 30, 2013 at 15:32
  • @Jim: My vardump looks like this: string(65) "[{"os":"iOS","hardware":"iPad"},{"os":"iOS","hardware":"iPhone"}]" vardump is my function which only wraps var_dump() in <pre> tags. Commented May 30, 2013 at 15:37
  • @FrédéricClausset: Thanks, once this gets sorted out I'll benchmark it and post the results here! Commented May 30, 2013 at 15:39
  • woah we missed the obvious ! of course this is always true if($string[0]!='{'||$string[0]!='[') , you need an && Commented May 30, 2013 at 15:45

2 Answers 2

2

I would be using json_decode only.

function isJson($string)
{
    return (json_decode($string) !== null);
}

But If you insist on checking the first chars, then I would use substr. And I believe your if statement should be using && instead of ||

if ($string[0] != '{' && $string[0] != '['){ .....

Or something like this

if (!in_array(substr($string, 0, 1), array('{', '[')))
    return false;
Sign up to request clarification or add additional context in comments.

Comments

0

json_encode returns false if the string is not valid Json.

function isValidJson($string) {
    if (json_encode($string) === false) {
        return false;
    }
    return true;
}

1 Comment

Thanks, I know that, but I think it'll be a performance improvement to instantly return false if the first character makes being valid json impossible. Will benchmark later.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.