Extract keys from JSON with motoko serde

is this the correct way of doing this or is there a more elegant solution @tomijaga

1 Like

I think you can use JSON.parse from json.mo

That will parse to a JSON value, and from there you could do something like:

import Array "mo:base/Array";

let keys: ?[Text] = switch (json) {
  case (#Object kvs) {
    ?Array.map<(Text, JSON), Text>(kvs, func ((k, _v)) {
  case (_) null;


To extract the keys, you need to parse the data into a variant structure like in @paulyoung’s example.
There isn’t a public function in the serde library for doing this for JSON text, but I can add a toCandid function that does that.

I use the same JSON library internally, so this is the best option for parsing and extracting the keys.

I’ve made some updates to the above code so that it extracts keys from nested arrays and objects


Thanks for both of your inputs, but for what I wanted to do I actually still like my solution more :smiley:

1 Like