How To Properly Return JSON From Your PHP Code

JavaScript Object Notation (JSON) is nothing more than a string with a specific format. It enables JavaScript to easily send and receive data to and from a server, no matter the back-end language.

A client of mine recently had an issue where a JavaScript error was being thrown during an AJAX call. The response was not valid JSON, and when parsing the result this error was thrown:

SyntaxError: Unexpected token in JSON at position

Although this error appeared in the JavaScript, the fault is really with the back-end not returning a properly formatted JSON string. When JavaScript attempts to parse the response, it runs across an invalid character and blows up.

What Not To Do

In my client’s case, the PHP code that was returning data to the server looked something like this:

<?php 
$badString = 'hi \r\n mom';
$color = 'green';
$cereal = 'lucky charms';
echo '{"thisWillBlowUp":"'.$badString.'","color":"'.$color.'","cereal":"'.$cereal.'"}';
?>

The client was manually formatting the JSON syntax and interpolating the variables into it. When this JSON-like string then gets parsed by the front end, the error occurs because the special characters \r\n were not properly escaped. Manually formatting the JSON string like this is not recommended and will lead to problems down the line.

All modern server-side languages have helper functions for properly formatting a JSON string built right into the framework. This PHP function is called json_encode(…) and will handle the JSON syntax, character escaping, and heavy lifting for you.

A Code Example

<?php 
$badString = 'hi \r\n mom';
$color = 'green';
$cereal = 'lucky charms';

//construct a PHP array or object here to hold the values
$response = array(
	"noLongerAnIssue" => $badString,
	"color" => $color,
	"cereal" => $cereal
);

echo json_encode($response);
?>

This not only looks cleaner, but will alleviate the JavaScript error that was seen before. The PHP function json_encode will format the array into a proper JSON string and escape the special \r\n characters.

Leave a Reply

Your email address will not be published. Required fields are marked *