olosegres/jsona

How to deserialize duplicate id without having duplicate result?

rigorcadiz opened this issue · 1 comments

I have this JSON API data format:

{
  "meta": {
    "page": {
      "current-page": 1,
      "per-page": 25,
      "from": 1,
      "to": 2,
      "total": 2,
      "last-page": 1
    }
  },
  "data": [{
      "type": "brands",
      "id": "105",
      "attributes": {
        "name": "Brand A",
        "status": "pending",
        "company_id": 1
      },
    },
    {
      "type": "brands",
      "id": "105",
      "attributes": {
        "name": "Brand A",
        "status": "approved",
        "company_id": 2
      },
    }
  ]
}

But when I perform jsona.deserialize(data), I get this as result:

[{
  type: "brands"
  id: "105"
  name: "Brand A"
  status: "pending"
  company_id: 1
},
{
  type: "brands"
  id: "105"
  name: "Brand A"
  status: "pending"
  company_id: 1
}]

Hi, your type-id isn't unique, it shouldn't be like that.

But if you want to work with such ornery json, you may extend DeserializeCache and pass it to Jsona.

import Jsona from 'jsona';

class MyDeserializeCache extends DeserializeCache {
  createCacheKey(data: TJsonApiData, resourceIdObject?: TResourceIdObj) {
     return ''; // todo write your logic to identify unique items here
  }
}

export const dataFormatter = new Jsona({
    DeserializeCache: MyDeserializeCache
});