You can use TextDecoder:
try {
parsedJson = JSON.parse(new TextDecoder().decode(response as ArrayBuffer));
} catch (e) {
parsedJson = {};
}
In my case the request is waiting for an ArrayBuffer response, but if an error occours on the backend, I get a JSON object containing the error. I check if the response is an error with this code.
The try-catch block is needed because if the ArrayBuffer is not a json, then the JSON.parse() method will throw an error.
Answer from Bence Szabó on Stack OverflowYou can use TextDecoder:
try {
parsedJson = JSON.parse(new TextDecoder().decode(response as ArrayBuffer));
} catch (e) {
parsedJson = {};
}
In my case the request is waiting for an ArrayBuffer response, but if an error occours on the backend, I get a JSON object containing the error. I check if the response is an error with this code.
The try-catch block is needed because if the ArrayBuffer is not a json, then the JSON.parse() method will throw an error.
This wokrs for me :
String.fromCharCode.apply(null, new Uint8Array(replaceThisByYourData))
How to convert arrayBuffer to JSON in React
JS: How to convert ArrayBuffer to string?
How to read JSON error response from $http if responseType is arraybuffer
node.js - Typescript how to use ArrayBuffer data made of JSON - Stack Overflow
» npm install json-arraybuffer-reviver
Working with Web Push Notifications.
https://developer.mozilla.org/en-US/docs/Web/API/PushSubscription
I got the Push Subscription Object.
I get the keys for p256dh and auth, using PushSubscription.getKey()
Unfortunately, getKey() returns an ArrayBuffer per the docs.
I need to save this subscription object with JSON.stringify(), specifically because I am creating a new object and can't use the toJSON() method which is part of the original Push Subscription Object.
When converting to JSON , ArrayBuffer disappears. So I get an empty object.
Thus, I need to convert the ArrayBuffer to a string before sending to the server.
How do I do this? I saw the Buffer suggested, but thats only available on server side.
Edit: As @Paul LeBeau points out, my answer assumes that the response is ASCII encoded.
Basically you just need to decode the ArrayBuffer into a string and use JSON.parse().
var decodedString = String.fromCharCode.apply(null, new Uint8Array(data));
var obj = JSON.parse(decodedString);
var message = obj['message'];
I ran tests in IE11 & Chrome and this works just fine.
@smkanadl's answer assumes that the response is ASCII. If your response is in another encoding, then that won't work.
Modern browsers (eg. FF and Chrome, but not IE yet) now support the TextDecoder interface that allows you to decode a string from an ArrayBuffer (via a DataView).
if ('TextDecoder' in window) {
// Decode as UTF-8
var dataView = new DataView(data);
var decoder = new TextDecoder('utf8');
var response = JSON.parse(decoder.decode(dataView));
} else {
// Fallback decode as ASCII
var decodedString = String.fromCharCode.apply(null, new Uint8Array(data));
var response = JSON.parse(decodedString);
}
» npm install json-bufferify
I had check your code. But can't get your output
my server code is:
const WebSocketServer = new require('ws');
let webSocketServer;
const initServer = async() => {
let port = 8091;
webSocketServer = new WebSocketServer.Server({ port });
webSocketServer.binaryType = 'arraybuffer';
console.log(`Server start on port: ${port}`)
webSocketServer.on('connection', function(ws) {
ws.send(
JSON.stringify({
"market": "United States",
"current_price": 645.00000000,
"highest_price": 887.00000000,
}),
)
});
}
initServer();
and client code is:
<script>
const ws = new WebSocket("ws://localhost:8091");
ws.binaryType = 'arraybuffer';
ws.onmessage = function(message){
console.log(JSON.parse(message.data));
}
</script>
output is object:

if you read data from json file try this code:
const readData = (path) => {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', function(err, contents) {
if (!err) resolve(JSON.parse(contents))
else reject(Error(`The fail "${path}" is not read`))
});
});
}
also try this function:
const arrayBufferToString(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
So the problem was the WebSocket library I was using.
I was using the 'ws' library, and it seems it cannot recognise data converted via .binaryType.
Once I removed the library and use the original WebSocket that Node.js provides, everything is good to go.
I appreciate everyone's try helping me.