Search code examples
javascriptcbor

cbor encoding dictionary with int key(s) turn to string key(s) on the server side


# client side code:
import {encode, decode} from "cbor-js"
const data = {1: 1, 2: 2, 3: :3}
const encoding = encode(data)

after sending the encoded data into the server (python) and decoding it I am receiving:

data = {"1": 1, "2": 2, "3": 3}

instead of :

data = {1:1, 2:2, 3:3}

Solution

  • my solution was to modify the cbor-js lib so it'll also handle a Map type

    encodeItem function:

    else if (value instanceof Map){
      var keys = Array.from(value.keys());
      length = keys.length;
      writeTypeAndLength(5, length);
      for (i = 0; i < length; ++i) {
        var key = keys[i];
        encodeItem(key);
        encodeItem(value.get(key));
      }
    }
    

    decodeItem addition:

    case 5:
       function isStringType(val) {
          return typeof val === "string"
       }
       var retObject = new Map();
       for (i = 0; i < length || length < 0 && !readBreak(); ++i) {
           var key = decodeItem();
           retObject.set(key, decodeItem())
       }
       const allKeysAreStrings = Array.from(retObject.keys()).every(isStringType)
       if (allKeysAreStrings){
           retObject = Object.fromEntries(retObject)
       }
       return retObject;