user9348468
user9348468

Reputation:

JSON_ERROR_UTF8(5) error while json_decode

I am trying to read a JSON file that contains an array of objects located in laravel storage and trying to iterate it. My attempt is as below.

$json = Storage::disk('local')->get('users.json');
json_decode($json, true);

This will return string type for the $json. So I cannot iterate. Anyone knows where I got wrong and how can I fix it?

Below is the part of my $json output.

[
  {
    "_id": 1,
    "url": "http://initech.tokoin.io.com/api/v2/users/1.json",
    "external_id": "74341f74-9c79-49d5-9611-87ef9b6eb75f",
    "name": "Francisca Rasmussen",
    "alias": "Miss Coffey",
    "created_at": "2016-04-15T05:19:46 -10:00",
    "active": true,
    "verified": true,
    "shared": false,
    "locale": "en-AU",
    "timezone": "Sri Lanka",
    "last_login_at": "2013-08-04T01:03:27 -10:00",
    "email": "[email protected]",
    "phone": "8335-422-718",
    "signature": "Don't Worry Be Happy!",
    "organization_id": 119,
    "tags": [
      "Springville",
      "Sutton",
      "Hartsville/Hartley",
      "Diaperville"
    ],
    "suspended": true,
    "role": "admin"
  },
  {...}
]

Edit: json_decode_error function returns 5 which is unsupported utf8 characters included in the file is the issue.

Upvotes: 0

Views: 592

Answers (1)

Dark Knight
Dark Knight

Reputation: 6541

Handle json_decode error as follow using json_last_error.

if ($json === null && json_last_error() !== JSON_ERROR_NONE) {
   echo "Incorrect json data.";
}

If you've unsupported UTF-8 characters in your encoded json then convert them before decoding.

$input = Storage::disk('local')->get('users.json');
$json = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($input));
$arr = json_decode($json, true);

If possible I suggest you to do the same while doing json_encode.

Upvotes: 1

Related Questions