The mobile app developers wants an api to get a list of articles from our Drupal site. It should have these fields in the output:

  1. nid
  2. title
  3. field_teaser_body

The api resonse has to be in JSON format.

The field type of field_teaser_body field is Long text and text processing is Plain text.

I created a custom code to get this working. Here's a simplified version of it.

$query = db_select('node', 'n');

  ->fields('n', array('nid', 'title'))
  ->condition('n.status', 1)
  ->orderBy('n.created', 'DESC')

$result = $query->execute();

$nodes = array();
foreach ($result as $value) {
  $node = node_load($value->nid);

  $data = array(
    'nid' => $node->nid,
    'title' => $node->title,
    'field_teaser_body' => !empty($node->field_teaser_body['und'][0]['value']) ? check_plain($node->field_teaser_body['und'][0]['value']) : '',

  $data = (object) $data;
  array_push($nodes, $data);

$content = new stdClass();
$content->nodes = $nodes;

print json_encode($content);

Just for the security purpose, I'm using check_plain() function to sanitize the teaser body text. But, when using this function, it encodes all special characters.

For e.g., Bob's height is > than Alice. converts to Bob's height is > than Alice.

The mobile app developers said that they don't want any encoded text in the JSON output.

Is it a safe practice to send the unencoded (unsanitized) text in the JSON output ?

  • Just a note, but perhaps better to use drupal_json_encode than json_encode. Commented Oct 6, 2015 at 2:51

2 Answers 2


There is no need to encode or escape anything yourself. json_encode() will take care of properly escaping any special purpose characters.


From a Drupal standpoint, it's ok to send markup in JSON fields.

After all, you're delivering the content which may need markup to work (e.g. <p> & <h1> tags for formatting). The onus should be on the app developer consuming the JSON to do sanitary checks (e.g. <script> injection, broken markup, malicious <iframe>, etc.). If you have any custom input forms that's where you should be doing your sanitary checks.

With all that said, if security is a concern, I'd suggest looking at a ready made solution for delivering content in a JSON format (e.g. Services). Any community-provided module solution is likely to have more security vetting than your own solution.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.