skip to Main Content

I am confused about this issue i am having

I recieve this Json object as a Websocket message from a hardware device, the property uiAppMsg is encoded in base64 so I decode it and then want to reassign it to the uiAppMsg in the jsonObj but when I run this in my app, it does not update the value of jsonObj.uiAppMsg and in the following lines i can still see its value as the encoded string, when i try to do this in JSFiddle for example it decodes the string properly and I can see the objects attribute value updated as the decoded Json Object. Am i missing something basic here why it wouldnt be working in the app. So basically I want to reassign the uiAppMsg Property on the object with the decoded string.

let socketMsg = "{"msgType":"uiAppMsg","uiAppMsg":"eyJ0cmFuc2FjdGlvbkRhdGEiOnsiQnJkU3RhdHVzRGlzcGxheSI6eyJEaXNwbGF5VGV4dCI6IkFMUkVBRFkgbmV3bGluZSBPTkJPQVJEIiwidGltZXIiOiIiLCJjb2xvciI6IiJ9fSwidHJhbnNhY3Rpb25UaW1lb3V0RGF0YSI6eyJCcmRTdGF0dXNEaXNwbGF5Ijp7IkRpc3BsYXlUZXh0IjoiIiwidGltZXIiOiIiLCJjb2xvciI6IiJ9fX0="}"
var jsonObj = JSON.parse(socketMsg);
const decodedUIAppMsg = atob(jsonObj.uiAppMsg);
jsonObj.uiAppMsg = JSON.parse(decodedUIAppMsg);

console.log(jsonObj)

2

Answers


  1. Chosen as BEST ANSWER

    @cmgchess thanks for your suggestion, it works to reassign it that way!


  2. Both JSON.stringify and atob should work in Angular.

    Here are two alternatives that use destructuring/spread, and a functional approach that reduces the object.

    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; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search