0

I'm working on a careers listing page for our company. We are using an API to retrieve the information from our HR software provider. The JSON appears to be invalid. I'm using the below to test it.

<?php
     //Testing if ADPs json is valid
     $json = json_decode($jsondata);
     if (json_last_error() === JSON_ERROR_NONE) {
        // $json contains a valid json string. It's ready to use.
        print_r($jobdata);
     } else {
        // oops, it's not valid JSON.
        echo '<h2>'.'We\'re sorry. We are unable to list jobs right now. Please contact'.' <a href="mailto:careers@domain.com">careers@domain.com</a>'.'</h2>';
     }
  ?>

Is there a way I can parse the invalid JSON? It appears that there is an unexpected bracket somewhere.

  • 1
    Find the errors using [JSONLint](http://jsonlint.com/) and fix the software that created them. Even though it's technically possible to create a bracket-matching cleaning script, it might be impossible to unambiguously recreate the data. – jDo Jun 13 '16 at 13:32
  • Already checked this [post](http://stackoverflow.com/questions/17752948/php-invalid-characters-in-json-decode)? – Stacked Jun 13 '16 at 13:35
  • The whole point of JSON is that it's a standardised format. If the data doesn't conform to the standard then it isn't JSON, and the JSON decoding functions in PHP and in any other language will just throw it out with an error. It is not possible to get `json_decode()` to accept an invalid JSON string. You will have to fix the JSON first and then decode it. – Simba Jun 13 '16 at 14:11

1 Answers1

0

json_decode is failing for a reason. Do you really want to deserialize malformed data and further base your logic on such data?

Again, before manually decoding anything check the following:

  • Is the server returning data character-encoded in an encoding not expected by your application. Especially if your backend is running on an linux-based server and the 3rd party API on windows one
  • Is the JSON not further encoded by your application internal logic. A good try would be to check for encoded html entities and/or decode them with html_entity_decode()

From my experience - if such problems persist, try to use an wrapper which automates previously mentioned steps for you (and translated semi-json expressions, like mongodb queries, javascript expressions):

https://github.com/zendframework/zend-json

Tomasz
  • 99
  • 2
  • 6