我对我遇到的这个问题感到困惑
我从硬件设备接收这个 Json 对象作为 Websocket 消息,属性 uiAppMsg 以 base64 编码,因此我对其进行解码,然后想将其重新分配给 jsonObj 中的 uiAppMsg,但是当我在我的应用程序中运行它时,它没有更新 jsonObj.uiAppMsg 的值,在下面的行中,我仍然可以将其值视为编码字符串,当我尝试在 JSFiddle 中执行此操作时,它会正确解码字符串,并且我可以看到对象属性值更新为解码后的值Json 对象。我是否缺少一些基本的东西,为什么它无法在应用程序中工作?所以基本上我想用解码后的字符串重新分配对象上的 uiAppMsg 属性。
let socketMsg = "{\"msgType\":\"uiAppMsg\",\"uiAppMsg\":\"eyJ0cmFuc2FjdGlvbkRhdGEiOnsiQnJkU3RhdHVzRGlzcGxheSI6eyJEaXNwbGF5VGV4dCI6IkFMUkVBRFkgbmV3bGluZSBPTkJPQVJEIiwidGltZXIiOiIiLCJjb2xvciI6IiJ9fSwidHJhbnNhY3Rpb25UaW1lb3V0RGF0YSI6eyJCcmRTdGF0dXNEaXNwbGF5Ijp7IkRpc3BsYXlUZXh0IjoiIiwidGltZXIiOiIiLCJjb2xvciI6IiJ9fX0=\"}"
var jsonObj = JSON.parse(socketMsg);
const decodedUIAppMsg = atob(jsonObj.uiAppMsg);
jsonObj.uiAppMsg = JSON.parse(decodedUIAppMsg);
console.log(jsonObj)
JSON.stringify
和 atob
都应该在 Angular 中工作。
这里有两种使用解构/扩展的替代方案,以及一种减少对象的函数方法。
let socketMsg = "{\"msgType\":\"uiAppMsg\",\"uiAppMsg\":\"eyJ0cmFuc2FjdGlvbkRhdGEiOnsiQnJkU3RhdHVzRGlzcGxheSI6eyJEaXNwbGF5VGV4dCI6IkFMUkVBRFkgbmV3bGluZSBPTkJPQVJEIiwidGltZXIiOiIiLCJjb2xvciI6IiJ9fSwidHJhbnNhY3Rpb25UaW1lb3V0RGF0YSI6eyJCcmRTdGF0dXNEaXNwbGF5Ijp7IkRpc3BsYXlUZXh0IjoiIiwidGltZXIiOiIiLCJjb2xvciI6IiJ9fX0=\"}";
// In-line
// =======
const { uiAppMsg, ...obj } = JSON.parse(socketMsg);
const result1 = { ...obj, uiAppMsg: JSON.parse(atob(uiAppMsg)) };
console.log(result1);
// Reusable function
// =================
const parseMsgAndDecodeFields = (msg, fields) =>
fields.reduce((result, field) =>
Object.assign(obj, {
[field]: JSON.parse(atob(result[field]))
}), JSON.parse(msg));
const result2 = parseMsgAndDecodeFields(socketMsg, ['uiAppMsg']);
console.log(result2);
.as-console-wrapper { top: 0; max-height: 100% !important; }