如何从base 58编码/解码JSON

uqzxnwby  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(161)

我正在尝试将JSON转换为base 58字符串

@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
}

字符串
我得到的结果是

VcRbAEBxqHxij6KcXFvG1v5ydF1VDCn1M4qtUVtxwgqstwxqT4srsH6XfrF2Pu7nt7wHuNDGSsjmaSe8BWnYhFfFZr4FSEoGAQTddyCGghNRep7o47RyyXzdFs9w14Y


然后,我尝试将编码的字符串转换回JSON,其中我使用编码的base 58作为输入/参数

@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
    }
}


但在这里我得到了一个错误:

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


我做错了什么?

8xiog9wr

8xiog9wr1#

baseXCodec.decode(base58)返回一个字符代码数组(参见package description)。您应该将它们Map到字符串并连接它们(使用空字符串)以获得正确的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);

字符串

相关问题