外来字符引起的JSON解析问题?

时间:2014-05-15 10:49:11

标签: javascript json node.js

我正在尝试从一个包含许多奇怪字符的API(东亚符号,卷曲引号等)中解析返回JSON数据的字段。我收到此错误,不知道如何解决它。有没有办法将请求响应转换为某种“逃避”坏文本的格式。 这是错误:

这是我的确切代码,对不起它已经很久了。

var fs = require('fs'),
    http = require('http'),
    request = require('request');

var url = 'http://app.sportstream.com/api/tagstream/tagStreamForStageTwoModeration?q={%22customerId%22:%22ABHoko14%22,%22type%22:{%22$in%22:[%22image%22,%22video%22]}}&_=_5555'
var firstTime = false
var m = 1

    function get() {
        console.log('ghghg')
        http.get(url, function(res) {
            var body = '';
            res.on('data', function(chunk) {
                body += chunk;
            });
            res.on('end', function() {
                body = JSON.parse(body)
                jParse(body)
                setTimeout(get, 5000)
            });
        }).on('error', function(e) {
            console.log("Got error: ", e);
            setTimeout(get, 5000)
        });
    }

    function jParse(info) {
        //data = JSON.parse(info)
        data = info
        entries = data.entries
        if (firstTime) {
            numEntries = 800 //entries.length
            firstTime = false
        } else {
            numEntries = 2
            //numEntries = entries.length - numEntries
            if (numEntries) {
                for (i = 0; i < numEntries; i++) {
                    type = entries[i]['type']
                    title = entries[i]['author']
                    if (type == 'video') {
                        url = entries[i]['ssMetaData']['videos']['standard_resolution']['url']
                        download(url, 'images/aFile.mp4', function() {
                            console.log('hello')
                        })
                    } else if (type == 'image') {
                        url = entries[i]['ssMetaData']['images']['standard_resolution']['url']
                        download(url, 'images/' + m + 'File.jpg', function() {
                            console.log('hello')
                        })

                    } else {
                        console.log('no data')
                    }
                    m++
                }
            }
        }
    }

get()

这是我的错误

undefined:1
����
^
SyntaxError: Unexpected token �
at Object.parse (native)

1 个答案:

答案 0 :(得分:1)

外国人;我假设你指的是UTF-8编码的字符串。

为什么不尝试在响应中设置Content-Type编码,如下所示:

http.get(url, function(res) {
    res.header("Content-Type", "application/json; charset=utf-8");