Response of http_request returns data in json format

Hey guys, I created a type

   public type User={
         name:Text;
         age:Nat;
         hobbies:[Text];
   };

Then I want to return User into a json format data in the Response of http_request.

         return {
             body = Text.encodeUtf8(USERJSON);
             headers = [("Content-Type","application/json;charset=utf-8")];
             status_code = 200;
         };

If I pass in the data directly, it is successful
body=Text.encodeUtf8("{name:'tom',age:11}");

So I need to construct this Text type data, the stupid way is to use Text.concat to splice into a paragraph of text.

I want to ask

  1. Is there any way to convert type data into Text or Blob?
  2. Is there any better way to splice a long text with parameters?

You can use debug_show to get a Text rendering of most values. But there is no JSON library for Motoko, let alone a generic conversion library. So you need to put your JSON together manually.

1 Like