2011-10-20 30 views
0

我打电话给谷歌自定义搜索瓦特/ Node.js尝试。我收到的结果很好,但是当我尝试使用JSON.parse(dataFromGoogle)解析JSON时,我在一些元素(html标题和片段; html标题中包含unicode转义序列,但我不确定w /这些片段有什么问题)。我可以让Google不寄回我的HTML标题,但我真的需要这些代码片段!谷歌自定义搜索API返回无效的JSON?

对此有一个很好的解决方法,或者我应该计划做一些额外的预处理以手动去除非法字符吗?

* *编辑:从这个

增加输出控制台搜索“小企业”使用谷歌

{ "kind": "customsearch#search", "url": { "type": "application/json", "template": "https://www.googleapis.com/customsearch/v1?q={searchTerms}&num={count?}&start={startIndex?}&hr={language?}&safe={safe?}&cx={cx?}&cref={cref?}&sort={sort?}&filter={filter?}&gl={gl?}&cr={cr?}&googlehost={googleHost?}&alt=json" }, "queries": { "nextPage": [ { "title": "Google Custom Search - small business", "totalResults": "42300", "searchTerms": "small business", "count": 10, "startIndex": 11, "inputEncoding": "utf8", "outputEncoding": "utf8", "safe": "off", "cx": "my_token" } ], "request": [ { "title": "Google Custom Search - small business", "totalResults": "42300", "searchTerms": "small business", "count": 10, "startIndex": 1, "inputEncoding": "utf8", "outputEncoding": "utf8", "safe": "off", "cx": "my_token" } ] }, "context": { "title": "IR undefined:60 "htmlTitle": "\u003cb\u003eSmall Business\u003c/b\u003e Health Care Tax Cre ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: Unexpected token ILLEGAL at Object.parse (native) at IncomingMessage. (/Users/pvencill/workspace/irslab/lib/searchEngine.js:44:35) at IncomingMessage.emit (events.js:64:17) at HTTPParser.onBody (http.js:119:42) at CleartextStream.ondata (http.js:1213:22) at CleartextStream._push (tls.js:291:27) at SecurePair._cycle (tls.js:565:20) at EncryptedStream.write (tls.js:97:13) at Socket.ondata (stream.js:40:26) at Socket.emit (events.js:64:17)

+0

他们的反应是什么样的? – Chance

+0

这是正确的JSON,除了它包含一些字段中的unicode转义。我过滤掉了这些字段作为临时修复,但最终我想拥有它们。我明天会发布我的工作,我正在我的工作机器上做。 – Paul

回答

1

哇,所以事实证明我完全误解了错误告诉我。它发生在包含unicode的字段上的事实是巧合。 真正的问题是,我正在调用处理部分分块响应的.on(“data”,...)处理程序中的JSON.parse;在块完成之前可能不是有效的JS语句终止符。处理它的正确方法是构建主体,然后使用(“结束”)来解析它。

 var message = ""; 
     https.get(options, function(res){ 
      res.setEncoding('utf8'); 
      res.on('data', function(data){ 
       message += data; 
      }); 

      res.on('end', function(){ 
       if(callback){ 
        var data = JSON.parse(message); 
        data.items = data.items || []; 
        callback(data); 
       } 
      }); 

      res.on('error', function(error){ 
       console.log("ERROR" + error.message); 
      }); 
+0

不错。不会猜到的。 – JayCrossler