尝试使用json解析nodejs获取语法错误

时间:2014-08-17 15:47:41

标签: json node.js

我正在尝试构建应用。我之前没有Java经验,最初打算通过LAMP做到这一点,但发现这不是最好的解决方案。所以我有点绿色

我在windows 8机器上使用nodejs进行开发。我从ebay api中提取数据。我试图解析我得到的JSON(不知道我在做什么)

我知道的代码坏了:

 JSON.parse(body);

JSON本身:

/**/_cb_findItemsByKeywords({"findCompletedItemsResponse":[{"ack":["Success"],"version":       ["1.12.0"],"timesta
mp":["2014-08-17T15:39:18.735Z"],"searchResult":[{"@count":"1","item":[{"itemId":    ["231283411176"],"title":["Nine West Te
ched Out Snap on Case for iPhone 5 Shoe Lover Hard Cover CHOP 3OM0z1"],"globalId":["EBAY-US"],"primaryCategory":[{"categ
oryId":["20349"],"categoryName":["Cases, Covers & Skins"]}],"galleryURL":["http:\/    \/thumbs1.ebaystatic.com\/m\/mFGCczOCC
B_D_F8sXXJ1QrA\/140.jpg"],"viewItemURL":["http:\/\/www.ebay.com\/itm\/Nine-West-Teched-Out-Snap-Case-iPhone-5-Shoe-Lover
-Hard-Cover-CHOP-3OM0z1-\/231283411176?pt=US_Cell_Phone_PDA_Cases"],"paymentMethod":["PayPal"],"autoPay":["false"],"post
alCode":["08003"],"location":["Cherry Hill,NJ,USA"],"country":["US"],"shippingInfo":[{"shippingServiceCost":[{"@currency
Id":"USD","__value__":"3.89"}],"shippingType":["Flat"],"shipToLocations":["Worldwide"],"expeditedShipping":["true"],"one
DayShippingAvailable":["true"],"handlingTime":["0"]}],"sellingStatus":[{"currentPrice":[{"@currencyId":"USD","__value__"
:"15.07"}],"convertedCurrentPrice":[{"@currencyId":"USD","__value__":"15.07"}],"sellingState":["EndedWithoutSales"]}],"l
istingInfo":[{"bestOfferEnabled":["false"],"buyItNowAvailable":["false"],"startTime":["2014-07-15T09:58:29.000Z"],"endTi
me":["2014-09-13T09:58:29.000Z"],"listingType":["FixedPrice"],"gift":["false"]}],"returnsAccepted":["true"],"condition":
[{"conditionId":["1500"],"conditionDisplayName":["New other (see details)"]}],"isMultiVariationListing":["false"],"disco
untPriceInfo":[{"originalRetailPrice":    [{"@currencyId":"USD","__value__":"19.99"}],"pricingTreatment":["STP"],"soldOnEbay
":["false"],"soldOffEbay":["false"]}],"topRatedListing":["true"]}]}],"paginationOutput":[{"pageNumber":["1"],"entriesPer
Page":["1"],"totalPages":["848492"],"totalEntries":["848492"]}]}]})

来自nodejs的错误:

SyntaxError: Unexpected token /
at Object.parse (native)
at Request._callback (C:\Users\WolJoshu\Desktop\temp\nodejs\index.js:45:11)
at Request.self.callback (C:\Users\WolJoshu\Desktop\temp\nodejs\node_modules\request\request.js:123:22)
at Request.EventEmitter.emit (events.js:98:17)
at Request.<anonymous> (C:\Users\WolJoshu\Desktop\temp\nodejs\node_modules\request\request.js:1047:14)
at Request.EventEmitter.emit (events.js:117:20)
at IncomingMessage.<anonymous> (C:\Users\WolJoshu\Desktop\temp\nodejs\node_modules\request\request.js:998:12)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:870:14
at process._tickCallback (node.js:415:13)

代码:

var request = require('request');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

//This defines what main page to load

app.get('/', function(req, res){
  res.sendfile('engine.html');
});

io.on('connection', function(socket){

// Simply lets us know when users connect and disconnect
console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });

//When data comes in do the following
  socket.on('incomingdata', function(msg){

//put the data back to the client
    io.emit('incomingdata',  msg);

//This builds the ebay request

    var url = "http://svcs.ebay.com/services/search/FindingService/v1";
    url += "?OPERATION-NAME=findCompletedItems";
    url += "&SERVICE-VERSION=1.0.0";
    url += "&SECURITY-APPNAME=deleted";
    url += "&GLOBAL-ID=EBAY-US";
    url += "&RESPONSE-DATA-FORMAT=JSON";
    url += "&callback=_cb_findItemsByKeywords";
    url += "&REST-PAYLOAD";
    url += "&keywords=" + msg;
    url += "&paginationInput.entriesPerPage=1";

//This puts the request in

    request(url, function (error, response, body) {
      if (!error && response.statusCode == 200) {

//Here is some experimental json parcing stuff
 JSON.parse(body);
//   console.log('Here is the parsed text: ' + sample);    

//This echos our search term to the console
    console.log('Here is the search term: ' + msg);

//this pumps it back in to the client in raw HTML

        io.emit('incomingdata', body );        
        console.log('incomingdata', body );        
      }
    })

  });


});

http.listen(3000, function(){
  console.log('listening on *:3000');
});'

1 个答案:

答案 0 :(得分:1)

错误消息表明该解析正在第一个字符上死亡&#39; /&#39 ;; JSON不接受评论,只接受JSON编码(双引号,对象和数组,ISO8601日期等)。

我能够在&#34; findItemsByKeyWords(&#34;和最后一个关闭的paren,并将其发送到http://jsoneditoronline.org/之间去掉JSON有效负载,以验证它是否解析,以便&#39; s好的。但是你需要确保主体只包含有效的JSON,或者预处理去除前导注释和#34; findBy&#34;在解析之前调用。你可能还想将标题设置为&#34 ;接受&#34; JSON,如果这是你想要的。