DEV Community

Simon Hafner
Simon Hafner

Posted on

Decoding CBOR with PureScript

If you want to decode cbor data from PureScript, there's cborg, which works just fine... if you use useMaps to deal with the Error: CBOR decode error: non-string keys not supported (got number) errors. Afterwards you have javascript Maps, which can't be decoded with argonaut. I use this code as workaround:

const toObject = function(cbor) {
  if (cbor instanceof Map) {
    var obj = {}
    cbor.forEach(function(value, key) {
      obj[key.toString()] = toObject(value);
    });
    return obj;
  } else {
    if (cbor instanceof Array) {
      return cbor.map(ob => toObject(ob));
    } else {
      if (cbor instanceof Object) {
        var obj = {}
        cbor.forEach(function(value, key) {
          obj[key.toString()] = toObject(value);
        });
        return obj;
      } else {
        return cbor
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

After that, you can decode the tags as string keys, e.g.

decodeJson cbor :: _ { "1" :: Int }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)