How to Convert Object To Text

I’m trying to convert object in to string. I want this kind of output. it is possible?

public type CartKeyData = {
     id:Nat32;
     option:tempOption;
};

let hash = Text.hash(CartKeyData);

Text.hash only accepts type Text

  public func hash(t : Text) : Hash.Hash {
    var x : Nat32 = 5381;
    for (char in t.chars()) {
      let c : Nat32 = Prim.charToNat32(char);
      x := ((x << 5) +% x) +% c
    };
    return x
  };

So you can do let hash = Text.hash(debug_show(CartKeyData));

Also you are passing in a type. Make sure you pass in a record.

Can we convert it back to Object?

You maybe able to convert it back with GitHub - edjCase/motoko_candid.

You may also be interested in the .to_candid and .from_candid methods. They use binary but maybe that works for you? Apparently, this binary object is not-deterministic so you should be careful if relying on it for a hash.

2 Likes