Hyperledger Fabric JS链码查询返回[object Object]问题求助
问题根因
Hyperledger Fabric JavaScript SDK调用链码函数时,所有传入的参数都会被自动转换为字符串类型。你直接传入数组/对象类型的参数时,SDK会默认调用该值的toString()方法进行转换:
- 普通对象执行
toString()返回结果为固定的[object Object] - 数组执行
toString()会将内部每个元素执行toString()后用逗号拼接
所以你调用CreateItem上传数据时,数组字段在传入链码前就已经被转换成了错误的字符串格式,存入账本的内容本身就是异常的,和后续查询逻辑无关。
解决方案
步骤1:客户端传参前序列化数组字段
调用CreateItem接口前,先将所有数组/对象类型的参数通过JSON.stringify()序列化为JSON字符串,再作为参数传入链码:
// 示例参数处理逻辑 const uploadData = { "plantCode": "test", "plantName": "test", "productionDate": "2021-03-25", "productCode": "test", "productName": "test", "lotNo": "test", // 数组字段先序列化 "rmInfors": JSON.stringify([ { "code": "test", "name": "test", "lotNo": "test" } ]), "premixInfors": JSON.stringify([ { "code": "test", "name": "test", "lotNo": "test" }, // 其余元素保持原有结构即可 ]), "packageInfors": JSON.stringify([ { "code": "test", "name": "test", "lotNo": "test" }, // 其余元素保持原有结构即可 ]), "process": "test", "owner": "test", "transactionDate": "2021-04-23", "email": "test@test.com" } // 再将uploadData的字段作为参数调用CreateItem链码函数
步骤2:链码层反序列化参数后存储
修改链码中的CreateItem方法,拿到序列化后的数组参数字段后,先通过JSON.parse()转回数组再存入账本:
async CreateItem(ctx , plantCode, plantName, productionDate, productCode, productName, lotNo, rmInfors, premixInfors , packageInfors , process , owner , transactionDate, email) { const exists = await this.ItemExists(ctx, productCode); if(exists) { throw new Error(`The item ${productCode} already exists`); } // 新增参数反序列化逻辑 const parsedRmInfors = JSON.parse(rmInfors); const parsedPremixInfors = JSON.parse(premixInfors); const parsedPackageInfors = JSON.parse(packageInfors); let item = { docType: 'item', plantCode: plantCode, plantName: plantName, productionDate: productionDate, productCode: productCode, productName: productName, lotNo: lotNo, rmInfors: parsedRmInfors, premixInfors: parsedPremixInfors, packageInfors: parsedPackageInfors, process: process, owner: owner, transactionDate: transactionDate, email: email }; await ctx.stub.putState(productCode, Buffer.from(JSON.stringify(item))); let indexName = 'Code~name'; let codeNameIndexKey = await ctx.stub.createCompositeKey(indexName, [item.productCode, item.productName]); await ctx.stub.putState(codeNameIndexKey, Buffer.from('\u0000')); }
步骤3:验证效果
重新部署修改后的链码,重新上传测试数据,再调用QueryItems接口即可返回完整的数组字段内容,无需修改现有查询逻辑。
内容的提问来源于stack exchange,提问作者Specter_9
相关产品推荐
相关产品推荐

