jsontypescriptbase58

How to encode/decode JSON to/from base58


I am trying to convert the json into the base58 string

@Get('/test/v1.0/user-params-base58')
@ApiOperation({ summary: 'UserParamsBase58' })
async getParams(): Promise<any> {
    const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
    const baseXCodec = baseX(BASE58_ALPHABET);

    // Encode the JSON object to Base58
    const jsonData = {
        name: 'john',
        address: {
            street: 'liberty street',
            postal: 'ABC123',
            city: 'liberty city'
        },
    };

    const jsonStr = JSON.stringify(jsonData);
    const base58Encoded = baseXCodec.encode(Buffer.from(jsonStr, 'utf8'));
    console.log('Base58 Encoded:', base58Encoded);

    return base58Encoded
}

The result which I am getting is

VcRbAEBxqHxij6KcXFvG1v5ydF1VDCn1M4qtUVtxwgqstwxqT4srsH6XfrF2Pu7nt7wHuNDGSsjmaSe8BWnYhFfFZr4FSEoGAQTddyCGghNRep7o47RyyXzdFs9w14Y

Then I am trying to convert the encoded string back to JSON where I am using the encoded base58 as input/parameter

@Get('/test/v1.0/user-params-json')
@ApiOperation({ summary: 'UserParamsJson' })
async getJson(@Query('o') base58: string): Promise<any> {
    const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
    const baseXCodec = baseX(BASE58_ALPHABET);

    // Decode the Base58 string back to a JSON string
    const decodedJSONString = baseXCodec.decode(base58).toString();

    try {
        // Parse the JSON string into a JavaScript object
        const decodedObject = JSON.parse(decodedJSONString);
        console.log('Decoded JSON:', decodedObject);
        return decodedObject;
    } catch (error) {
        console.error('Error decoding Base58 data:', error);
        return null; // Handle any decoding errors here
    }
}

But here I am getting an error:

Error decoding Base58 data: SyntaxError: Unexpected non-whitespace character after JSON at position 3 (line 1 column 4)
   at JSON.parse (<anonymous>)
   at UserController.getJson (C:\Users\admin\code\src\pats\user.controller.ts:86:40)
   at C:\Users\admin\code\node_modules\@nestjs\core\router\router-execution-context.js:38:29
   at processTicksAndRejections (node:internal/process/task_queues:95:5)
   at C:\Users\admin\code\node_modules\@nestjs\core\router\router-execution-context.js:46:28
   at C:\Users\admin\code\node_modules\@nestjs\core\router\router-proxy.js:9:17

What am I doing wrong?


Solution

  • baseXCodec.decode(base58) returns an array of character codes (see package description). You should map them to strings and join them (with empty string) in order to get a proper JSON:

    baseX = require('base-x')
    
    base58 = "VcRbAEBxqHxij6KcXFvG1v5ydF1VDCn1M4qtUVtxwgqstwxqT4srsH6XfrF2Pu7nt7wHuNDGSsjmaSe8BWnYhFfFZr4FSEoGAQTddyCGghNRep7o47RyyXzdFs9w14Y"
    const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
    const baseXCodec = baseX(BASE58_ALPHABET);
    
    // Decode the Base58 string back to a JSON string
    const charCodeArray = Array.from(baseXCodec.decode(base58));
    const decodedJSONString = charCodeArray.map(x => String.fromCharCode(x)).join('');
    const decodedObject = JSON.parse(decodedJSONString);