String To Array

I used JSON.stringify() to store text in backend. i get the result like this “[10,11,12,9]” but i want an array like [10,11,12,9] to use in for loop . how to remove “” form this. i try the Text.trimStart and Text.split(obj, #char ‘/"’) but it is not working. how do i solve this problem.

I would say Text.tokens should do the trick if you call it with a pattern that matches any of these four characters: " ,
See: Text | Internet Computer Home
That gives you an iterator that you can use in your loop.

You may still have to convert the text 10, 11, etc to type Nat if that’s your application.

But how to make it dynamic. can you provide some example using “[10,11,12,9]” so i can make for loop using this array and get the data for each key.

I’m not sure if this needs updating but it might be a good place to start:

import Text "mo:base/Text";
import Iter "mo:base/Iter";

actor {
  let t : Text = "\"[10,11,12,9]\"";

  public func f() : async [Text] {
    var s = t;
    s := Text.trimStart(s, #text "\"[");
    s := Text.trimEnd(s, #text "]\"");
    let i = Text.tokens(s, #char ',');
    Iter.toArray<Text>(i);
  };
}

It’s not very robust though. Additional spaces can break it. You’d have to trim them, too.

Thanks paulyoung.
this motoko-json needs improvement.

it’s give me this kind of error.
base/Text.mo:259.15-259.20: internal error.