tomexsans
tomexsans

Reputation: 4527

Can we detect JSON Errors

I'm using json_encode() and the files that I am using will be parsed to a JavaScript grid.

For example:

Index.php has the JavaScript that calls data.php, where I parse my PHP arrays to JSON. The question is, is there a way to know if Index.php is getting the data right. Some kind of debug?

Upvotes: 1

Views: 592

Answers (6)

jribeiro
jribeiro

Reputation: 3463

json_decode will return NULL if it fails:

if (json_decode($your_json_var, true) === NULL)
{
    // NULL is returned if the json cannot be decoded or if the 
    // encoded data is deeper than the recursion limit.
}

To make this perfectly save, compare against 'null' as well:

if (json_decode($json, true) === NULL && $json !== 'null')
{
    // NULL is returned if the json cannot be decoded or if the 
    // encoded data is deeper than the recursion limit.
}

It's advised to use PHP 5.3 or higher, it offers access to json_last_error which returns !== JSON_ERROR_NONE when an error condition did happen.

Upvotes: 2

Marc B
Marc B

Reputation: 360632

Since json_decode can potentially return a literal TRUE, FALSE, or NULL value, the only 100% safe way to check for problems is json_last_error:

if (json_last_error() !== JSON_ERROR_NONE) {
   ... decoded with error ...
}

Of course, this was added in PHP 5.3 only. Prior to this, you'd have to check for expected data in the returned structure.

Upvotes: 2

Erik Giberti
Erik Giberti

Reputation: 1235

If you are using a library such as jQuery for your JavaScript interaction, it can raise an error event if you choose to monitor it. See 'error' here: http://api.jquery.com/jQuery.ajax/

You can also call the data.php file directly in your browser see if there data your expecting is what's being returned.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074238

...is there a way that you may know if Index.php is getting the data right. Or some kind of debug?

If you're using a proper client-side debugger (and there's no excuse not to be in 2012!), you can see the data going back and forth to the server using the "Network" tab or similar. I assume you're not expecting json_encode to produce invalid JSON so much as not quite the data you were expecting (e.g., you're experimenting with the structure, etc.). You can copy the data that's sent back to the client, and then paste it into http://jsonlint.com to reformat it so you can see the end result.

Upvotes: 1

Teun Zengerink
Teun Zengerink

Reputation: 4393

You can use something like Firebug for Firefox or Chrome's Developer Tools to check your JavaScript.

Use JSONLint to verify your JSON.

Upvotes: 1

Vitamin
Vitamin

Reputation: 1526

Your Index.php script should return a status code to indicate failure or success.

See RFC 2616 - 10 Status Code Definitions

Upvotes: 1

Related Questions