Check valid JSON with jQuery

Programming Oct 05, 2017

If you receive json data from an external service, you should make sure if the data is a proper formed json. With this code you can quickly test the data.

This is just a quick hint for the validation of JSON (JavaScript Object  Notation). If you do AJAX requests, you probably use JSON to transmit  your data objects. But if the response is not valid, your code of your  callback function presumably do not work as expected.

That can be a risk, because the user looks for a visual feedback. The error is only printed in the console.

$.ajax(
            {
                url: 'example.com',
                success: function (response) {
                    var encodedJson;
                    try{
                         //try to parse JSON
                         encodedJson = $.parseJSON(response);
 
                         //use JSON
                         encodedJson.name
                    }catch(error){
                         //handle error -> visual feedback for user
                    }
                }
            }
      );

Please comment below, if you have any questions.

Credits:

Stefan

Howdy! I'm Stefan and I am the main author of this blog. If you want know more, you can check out the 'About me' page.

Impressum | Data Privacy Policy | Disclaimer
Copyright: The content is copyrighted and may not be reproduced on other websites without permission.