0

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.

7
  • store json_decode output in another variable and you can loop over that. Commented Oct 18, 2020 at 6:50
  • then it will return null for the new variable Commented Oct 18, 2020 at 6:55
  • can you include in question what do you have in your $json variable. Include output of echo var_dump($json);die; in the question itself. Commented Oct 18, 2020 at 6:55
  • that returns an array of objects which contains around 1940 lines in notepad output Commented Oct 18, 2020 at 6:59
  • you can include only a subset which can give us an idea. We might need recursive json_decode, just in case. One more thing, if it is already an array of object then why you're doing json_decode. Commented Oct 18, 2020 at 7:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You very much. It returns the array now.

Your Answer

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