将 ArrayBuffer 响应转换为 JSON

Vis*_*hnu 9 javascript json arraybuffer angularjs

在这里,我调用 GetFile ,以 ArrayBuffer{} 对象的形式获取响应,如果我执行 response.errors=undefined,则在网络选项卡中响应为 {"errors":["photoProof Image is not available in the system"]}。

$scope.getDocuments = function(){
  Myservice.downLoadDocument('photo', $scope.user.mobileNo).
    then(function(response){
     })
}
Run Code Online (Sandbox Code Playgroud)

如果我这样做,网络选项卡中的值就会低于该值。

 response.byteLength = 64
Run Code Online (Sandbox Code Playgroud)

如何将此 ArrayBuffer 转换为正确的 JSON 格式?

小智 7

这对我有用:

String.fromCharCode.apply(null, new Uint8Array(replaceThisByYourData))
Run Code Online (Sandbox Code Playgroud)


小智 7

您可以使用TextDecoder

try {
  parsedJson = JSON.parse(new TextDecoder().decode(response as ArrayBuffer));
} catch (e) {
  parsedJson = {};
}
Run Code Online (Sandbox Code Playgroud)

在我的例子中,请求正在等待 ArrayBuffer 响应,但如果后端发生错误,我会得到一个包含错误的 JSON 对象。我检查此代码的响应是否有错误。

需要 try-catch 块,因为如果 ArrayBuffer 不是 json,那么 JSON.parse() 方法将抛出错误。


小智 3

也许你可以使用json-bufferify。它是一个帮助您在 JSON 和 ArrayBuffer 之间进行转换的模块,您可以在 Node.js 和浏览器中运行它。