[英]Get a JSON file (that contains Hebrew values) from a remote server and parse it in Node.js
我有一個托管在遠程服務器上的動態JSON文件(充當某種API),它的值中還包含一些希伯來語文本。
如何保存響應並將其解析為JSON對象?
到目前為止,這就是我使用Request( https://www.npmjs.org/package/request )的結果:
var options = {
url: 'http://www.AWEBSITEHERE.com/file.json',
method: 'GET'
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
// ...
}
}
request(options, callback);
並且此代碼在訪問時給出以下錯誤:
SyntaxError: Unexpected token �
at Object.parse (native)
at Request.callback [as _callback] (C:\Sites\node\proj\routes\inde
x.js:21:29)
at Request.self.callback (C:\Sites\node\proj\node_modules\request\
request.js:122:22)
at Request.EventEmitter.emit (events.js:98:17)
at Request.<anonymous> (C:\Sites\node\proj\node_modules\request\re
quest.js:1019:14)
at Request.EventEmitter.emit (events.js:117:20)
at IncomingMessage.<anonymous> (C:\Sites\node\proj\node_modules\re
quest\request.js:970:12)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
我認為此錯誤與服務器發送的BOM字符有關。
我怎么解決這個問題?
謝謝!
我認為您可能必須解碼響應主體(json):
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
body = body.toString('utf-8');
var info = JSON.parse(body);
}
}
另外,如果這不起作用,則可能是壓縮了主體,並且必須在解碼之前解壓縮:
var encoding = response.headers['content-encoding']
if(encoding && encoding.indexOf('gzip')>=0) {
body = uncompress(body);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.