NatLabs / serde

Serialization and Deserialization library for motoko
MIT License
16 stars 4 forks source link

JSON array to Motoko array #18

Closed padi-g closed 11 months ago

padi-g commented 1 year ago

Hi there, thanks a ton for this library! With my use case being a bit more complicated, I was wondering if you could update the sample to demonstrate how to convert a JSON payload of the following form to an array in motoko.

JSON payload -

{
   "message":"Give data retrieved successfully",
   "data":[
      {
         "parentNonprofits":[
            "vLvKLwLxUe94aCvbVbQS"
         ],
         "userId":"29zKJK2xytOQY3VR7JnbI9HIkPp2",
         "giverEmailId":"29zKJKS6CF7IH5vLvKLw@flockby.email",
         "giveId":"kPCeIOil0bN7zBnLE1hb",
         "createdOn":"2023-09-12T11:26:35.311000+00:00",
         "feathersAmount":3400,
         "giverId":"29zKJKS6CF7IH5vLvKLw",
         "projectId":"r6L8zEgEKFS2zsQB2Cc5"
      },
      {
         "parentNonprofits":[
            "vLvKLwLxUe94aCvbVbQS"
         ],
         "userId":"29zKJK2xytOQY3VR7JnbI9HIkPp2",
         "giverEmailId":"29zKJKS6CF7IH5vLvKLw@flockby.email",
         "giveId":"5M6bFh6Fb1yTd8LuLJrz",
         "createdOn":"2023-09-10T07:16:16.715000+00:00",
         "feathersAmount":800,
         "giverId":"29zKJKS6CF7IH5vLvKLw",
         "projectId":"r6L8zEgEKFS2zsQB2Cc5"
      }
   ]
}

I expect to be able to process it something like records.add(jsonObj.data) where records is a buffer or list data structure containing my custom type.

Essentially, how do I process a JSON array using this library and get an array/list/buffer object in motoko?

tomijaga commented 1 year ago

Hey @padig, Thanks for creating the issue! It prompted me to update the readme. I've included the conversion of an array data type from motoko to JSON and vice versa.

The important thing is to define the data type and ensure it is an exact match to the equivalent data type in motoko. For example, the createdOn field stores a date timestamp but in motoko, it is recognized as a Text

From this example, it seems like the data type is:

    type Record = {
        parentNonprofits: [Text];
        userId: Text;
        giverEmailId: Text:
        giveId: Text;
        createdOn: Text;
        feathersAmount: Nat;
        giverId: Text;
        projected: Text;
    }; 

    let #ok(blob) = JSON.fromText(jsonObj.data, null);
    let records: ?[Record] = from_candid(blob);