2

We are migrating a D7 site to D8 and I have an API endpoint that returns the current user that I need to migrate. In D7, I would do something like:

global $user;
$u = user_load($user->uid);
return drupal_json_output($u);

This ends up returning a body like:

{
  "uid": "1111",
  "name": "SomeUser",
  "roles": [
    "2": "authenticated",
    "3": "premium"
  ],
  "field_matched_nodes": [
    "und": [
      {
         "target_id": "2222"
      },
      {
        "target_id": "3333"
      }
    ]
  ],
  ...
}

Now in D8, I'm trying to mimic the same thing. The key is that the return body needs to be exactly that is was in D7, or else the apps we have that use this endpoint won't work until push and update to the apps and our users update their app version.

So I'm trying something like:

$uid = \Drupal::currentUser()->id();
$current_user = User::load($uid);

$user_json = \Drupal::service('serializer')->serialize($user, 'json');
return JsonResponse($user_json, 200)

This gets me the user object in JSON, but it's structure is like:

{
  "uid": [
    {
      "value": 1111
    }
  ],
  "name": [
    {
      "value": "SomeUser"
    }
  ],
  "field_matched_nodes": [
    {
      "target_id": 2222,
      "target_type": "node",
      "target_uuid": "3248789345-23894798324-328498234",
      "url": "/en/node/2222",
    },
    {
      "target_id": 3333,
      "target_type": "node",
      "target_uuid": "3248789345-23894798324-328498234",
      "url": "/en/node/2222",
    }
  ],
  ...
}

Some notable differences:

  • Roles isn't even included in D8, but is in D7,
  • Basic field values like name are nested as a value for key "value" in an object in an array in D8, where in D7 it was simply the value for the field key
  • Custom fields aren't nested under "und" like they are in D7

Is there some sort of D7 serializer for D8 that constructs User objects as the same json structure it did for D8? Id be surprised if this doesn't exist, as I'm sure I'm not the only one who migrated to D8 with a public API...

2
  • This is going into Drupal 8? Is this using Migrate?
    – Kevin
    Jan 21 at 3:12
  • No, it’s migrating a custom module, but the structure of the user object changed in D8, so I’m looking to serialize this object into a D7 Jason/associative array
    – BlondeSwan
    Jan 21 at 4:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.