gpt4 book ai didi

将消息传递给 API 时的 Javascript 对象编码/解码

转载 作者:行者123 更新时间:2023-11-29 21:47:56 28 4
gpt4 key购买 nike

我正在将消息传递到第三方消息队列,该消息队列将消息中继到我的队列监听器(全部在 node.js 服务器端)。该消息具有预定义格式,允许我定义“自定义属性”。当我提供基本类型(字符串、数字等)时这很好用,但是当我尝试在自定义属性中传递一个对象时,它失败了。

发送此消息:

var info = {foo: 100};
var message = {
body: 'some string',
customProperties: {
type: 1,
name: 'test',
info: info
}
};

返回此消息:

{
body: 'some string',
customProperties: {
type: 1,
name: 'test',
info: '[object Object]'
}
};

并发送此消息:

var info = {foo: 100};
var message = {
body: 'some string',
customProperties: {
type: 1,
name: 'test',
info: JSON.stringify(info)
}
};

返回此消息:

{
body: 'some string',
customProperties: {
type: 1,
name: 'test',
info: '\\"{\\"foo\\":100}\\"'
}
};

然后当我尝试使用 JSON.parse(customProperties.info) 对其进行解码时失败。我认为正在发生的事情是它在每个自定义属性上调用 .toString ?有什么想法可以在传递此消息时对简单对象进行编码/解码吗?

最佳答案

围绕此问题的一个解决方案是将 info 编码为另一种格式,这种格式在 Azure's ServiceBus 中的 setRequestHeaders() 调用期间不会被修改。 .您可以像在第二个解决方案中那样对字符串进行 JSON 编码,但随后您可以像这样对结果进行 Base64 编码:

var info = {foo: 100};
var message = {
body: 'some string',
customProperties: {
type: 1,
name: 'test',
info: btoa(JSON.stringify(info))
}
};

这将产生如下所示的 customProperties:

{type: 1, name: "test", info: "eyJmb28iOjEwMH0="}

然后为了解码,你只需做

var info = JSON.parse(atob(message.customProperties.info));

产生

{foo: 100}

关于将消息传递给 API 时的 Javascript 对象编码/解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30448694/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com