How to convert JSON to ArrayBuffer in TypeScript

1 Answer

0 votes
interface RobotData {
  name: string;
  age: number;
  city: string;
}

const jsonData: RobotData = { name: "R2D2", age: 86, city: "New York" };

/**
 * Converts a JSON object to an ArrayBuffer
 */
function jsonToBuffer(obj: RobotData): ArrayBuffer {
  // 1. Serialize to string
  const str: string = JSON.stringify(obj);
  
  // 2. Encode to UTF-8 Uint8Array
  const encoder: TextEncoder = new TextEncoder();
  const bytes: Uint8Array<ArrayBuffer> = encoder.encode(str);
  
  // 3. Return the underlying buffer
  return bytes.buffer;
}

const buffer: ArrayBuffer = jsonToBuffer(jsonData);
console.log(buffer); 


/*
run:

ArrayBuffer {
  [Uint8Contents]: <7b 22 6e 61 6d 65 22 3a 22 52 32 44 32 22 2c 22 61 67 65 22 3a 38 36 2c 22 63 69 74 79 22 3a 22 4e 65 77 20 59 6f 72 6b 22 7d>,
  byteLength: 42
}

*/

 



answered Mar 18 by avibootz
...