2017-06-17 107 views
0

我正在使用Node JS应用测试facebook leadgen api。 使用Facebook测试工具,我得到了Facebook的回复。当我尝试JSON.stringify()时,我得到了将循环结构转换为JSON错误。我如何获得领域领导的价值。如何解析来自facebook leadgen api的循环JSON响应?

测试数据从Facebook:

  { 
       "field": "leadgen", 
       "value": { 
       "ad_id": "444444444", 
       "form_id": "444444444444", 
       "leadgen_id": "444444444444", 
       "created_time": 1497678903, 
       "page_id": "444444444444", 
       "adgroup_id": "44444444444" 
       } 
      } 

我试着使用打印日志中的响应。但反应看起来像这样。我无法理解如何解析它。

ServerResponse { 
     domain: null, 
     _events: { finish: [Function: resOnFinish] }, 
     _eventsCount: 1, 
     _maxListeners: undefined, 
     output: [], 
     outputEncodings: [], 
     outputCallbacks: [], 
     outputSize: 0, 
     writable: true, 
     _last: false, 
     upgrading: false, 
     chunkedEncoding: false, 
     shouldKeepAlive: false, 
     useChunkedEncodingByDefault: false, 
     sendDate: true, 
     _removedHeader: {}, 
     _contentLength: null, 
     _hasBody: true, 
     _trailer: '', 
     finished: false, 
     _headerSent: false, 
     socket: 
     Socket { 
     connecting: false, 
     _hadError: false, 
     _handle: 
      TCP { 
      bytesRead: 611, 
      _externalStream: {}, 
      fd: 14, 
      reading: true, 
      owner: [Circular], 
      onread: [Function: onread], 
      onconnection: null, 
      writeQueueSize: 0, 
      _consumed: true }, 
     _parent: null, 
     _host: null, 
     _readableState: 
      ReadableState { 
      objectMode: false, 
      highWaterMark: 16384, 
      buffer: [Object], 
      length: 0, 
      pipes: null, 
      pipesCount: 0, 
      flowing: true, 
      ended: false, 
      endEmitted: false, 
      reading: true, 
      sync: false, 
      needReadable: true, 
      emittedReadable: false, 
      readableListening: false, 
      resumeScheduled: false, 
      defaultEncoding: 'utf8', 
      ranOut: false, 
      awaitDrain: 0, 
      readingMore: false, 
      decoder: null, 
      encoding: null }, 
     readable: true, 
     domain: null, 
     _events: 
      { end: [Object], 
      finish: [Function: onSocketFinish], 
      _socketEnd: [Function: onSocketEnd], 
      drain: [Object], 
      timeout: [Function], 
      error: [Function: socketOnError], 
      close: [Object], 
      data: [Function: socketOnData], 
      resume: [Function: onSocketResume], 
      pause: [Function: onSocketPause] }, 
     _eventsCount: 10, 
     _maxListeners: undefined, 
     _writableState: 
      WritableState { 
      objectMode: false, 
      highWaterMark: 16384, 
      needDrain: false, 
      ending: false, 
      ended: false, 
      finished: false, 
      decodeStrings: false, 
      defaultEncoding: 'utf8', 
      length: 0, 
      writing: false, 
      corked: 0, 
      sync: true, 
      bufferProcessing: false, 
      onwrite: [Function], 
      writecb: null, 
      writelen: 0, 
      bufferedRequest: null, 
      lastBufferedRequest: null, 
      pendingcb: 0, 
      prefinished: false, 
      errorEmitted: false, 
      bufferedRequestCount: 0, 
      corkedRequestsFree: [Object] }, 
     writable: true, 
     allowHalfOpen: true, 
     destroyed: false, 
     _bytesDispatched: 0, 
     _sockname: null, 
     _pendingData: null, 
     _pendingEncoding: '', 
     server: 
      Server { 
      domain: null, 
      _events: [Object], 
      _eventsCount: 2, 
      _maxListeners: undefined, 
      _connections: 1, 
      _handle: [Object], 
      _usingSlaves: false, 
      _slaves: [], 
      _unref: false, 
      allowHalfOpen: true, 
      pauseOnConnect: false, 
      httpAllowHalfOpen: false, 
      timeout: 120000, 
      _pendingResponseData: 0, 
      _connectionKey: '6::::5050' }, 
     _server: 
      Server { 
      domain: null, 
      _events: [Object], 
      _eventsCount: 2, 
      _maxListeners: undefined, 
      _connections: 1, 
      _handle: [Object], 
      _usingSlaves: false, 
      _slaves: [], 
      _unref: false, 
      allowHalfOpen: true, 
      pauseOnConnect: false, 
      httpAllowHalfOpen: false, 
      timeout: 120000, 
      _pendingResponseData: 0, 
      _connectionKey: '6::::5050' }, 
     _idleTimeout: 120000, 
     _idleNext: 
      TimersList { 
      _idleNext: [Circular], 
      _idlePrev: [Circular], 
      _timer: [Object], 
      _unrefed: true, 
      msecs: 120000, 
      nextTick: false }, 
     _idlePrev: 
      TimersList { 
      _idleNext: [Circular], 
      _idlePrev: [Circular], 
      _timer: [Object], 
      _unrefed: true, 
      msecs: 120000, 
      nextTick: false }, 
     _idleStart: 14449, 
     parser: 
      HTTPParser { 
      '0': [Function: parserOnHeaders], 
      '1': [Function: parserOnHeadersComplete], 
      '2': [Function: parserOnBody], 
      '3': [Function: parserOnMessageComplete], 
      '4': [Function: onParserExecute], 
      _headers: [], 
      _url: '', 
      _consumed: true, 
      socket: [Circular], 
      incoming: [Object], 
      outgoing: null, 
      maxHeaderPairs: 2000, 
      onIncoming: [Function: parserOnIncoming] }, 
     on: [Function: socketOnWrap], 
     _paused: false, 
     read: [Function], 
     _consuming: true, 
     _httpMessage: [Circular] }, 
     connection: 
     Socket { 
     connecting: false, 
     _hadError: false, 
     _handle: 
      TCP { 
      bytesRead: 611, 
      _externalStream: {}, 
      fd: 14, 
      reading: true, 
      owner: [Circular], 
      onread: [Function: onread], 
      onconnection: null, 
      writeQueueSize: 0, 
      _consumed: true }, 
     _parent: null, 
     _host: null, 
     _readableState: 
      ReadableState { 
      objectMode: false, 
      highWaterMark: 16384, 
      buffer: [Object], 
      length: 0, 
      pipes: null, 
      pipesCount: 0, 
      flowing: true, 
      ended: false, 
      endEmitted: false, 
      reading: true, 
      sync: false, 
      needReadable: true, 
      emittedReadable: false, 
      readableListening: false, 
      resumeScheduled: false, 
      defaultEncoding: 'utf8', 
      ranOut: false, 
      awaitDrain: 0, 
      readingMore: false, 
      decoder: null, 
      encoding: null }, 
     readable: true, 
     domain: null, 
     _events: 
      { end: [Object], 
      finish: [Function: onSocketFinish], 
      _socketEnd: [Function: onSocketEnd], 
      drain: [Object], 
      timeout: [Function], 
      error: [Function: socketOnError], 
      close: [Object], 
      data: [Function: socketOnData], 
      resume: [Function: onSocketResume], 
      pause: [Function: onSocketPause] }, 
     _eventsCount: 10, 
     _maxListeners: undefined, 
     _writableState: 
      WritableState { 
      objectMode: false, 
      highWaterMark: 16384, 
      needDrain: false, 
      ending: false, 
      ended: false, 
      finished: false, 
      decodeStrings: false, 
      defaultEncoding: 'utf8', 
      length: 0, 
      writing: false, 
      corked: 0, 
      sync: true, 
      bufferProcessing: false, 
      onwrite: [Function], 
      writecb: null, 
      writelen: 0, 
      bufferedRequest: null, 
      lastBufferedRequest: null, 
      pendingcb: 0, 
      prefinished: false, 
      errorEmitted: false, 
      bufferedRequestCount: 0, 
      corkedRequestsFree: [Object] }, 
     writable: true, 
     allowHalfOpen: true, 
     destroyed: false, 
     _bytesDispatched: 0, 
     _sockname: null, 
     _pendingData: null, 
     _pendingEncoding: '', 
     server: 
      Server { 
      domain: null, 
      _events: [Object], 
      _eventsCount: 2, 
      _maxListeners: undefined, 
      _connections: 1, 
      _handle: [Object], 
      _usingSlaves: false, 
      _slaves: [], 
      _unref: false, 
      allowHalfOpen: true, 
      pauseOnConnect: false, 
      httpAllowHalfOpen: false, 
      timeout: 120000, 
      _pendingResponseData: 0, 
      _connectionKey: '6::::5050' }, 
     _server: 
      Server { 
      domain: null, 
      _events: [Object], 
      _eventsCount: 2, 
      _maxListeners: undefined, 
      _connections: 1, 
      _handle: [Object], 
      _usingSlaves: false, 
      _slaves: [], 
      _unref: false, 
      allowHalfOpen: true, 
      pauseOnConnect: false, 
      httpAllowHalfOpen: false, 
      timeout: 120000, 
      _pendingResponseData: 0, 
      _connectionKey: '6::::5050' }, 
     _idleTimeout: 120000, 
     _idleNext: 
      TimersList { 
      _idleNext: [Circular], 
      _idlePrev: [Circular], 
      _timer: [Object], 
      _unrefed: true, 
      msecs: 120000, 
      nextTick: false }, 
     _idlePrev: 
      TimersList { 
      _idleNext: [Circular], 
      _idlePrev: [Circular], 
      _timer: [Object], 
      _unrefed: true, 
      msecs: 120000, 
      nextTick: false }, 
     _idleStart: 14449, 
     parser: 
      HTTPParser { 
      '0': [Function: parserOnHeaders], 
      '1': [Function: parserOnHeadersComplete], 
      '2': [Function: parserOnBody], 
      '3': [Function: parserOnMessageComplete], 
      '4': [...... 

回答

0

您可以使用此自定义字符串化功能,它可以处理循环依赖。这是标准的,我从别人那里偷走了它。

const customStringify = function (v) { 
    let cache = []; 
    return JSON.stringify(v, function (key, value) { 
    if (typeof value === 'object' && value !== null) { 
     if (cache.indexOf(value) !== -1) { 
     // Circular reference found, discard key 
     return; 
     } 
     // Store value in our collection 
     cache.push(value); 
    } 
    return value; 
    }); 
}; 

尽管如果您尝试解析响应,您可能希望调用JSON.parse而不是JSON.stringify。

+0

嘿,我成功转换的响应成JSON响应。使用该函数,我试图将其粘贴到JSON格式器工具,我得到多个json根元素错误。无论如何,我可以修改代码以获得正确的JSON格式。 – Anirudh

+0

发送upvote,我可以给你一个答案哈哈哥们 – Olegzandr

+0

JSON.stringify或这个customStringify函数应该生成适当的JSON ..小心地将它注销到某处,以便当你复制/粘贴它时,没有东西会被损坏。我不得不看JSON给你更多的信息。 – Olegzandr

1

最后经过很多次迭代的下面的代码解决了我的问题:

app.post('url', function(req, res) { 

const customStringify = function (res) { 
let cache = []; 
return JSON.stringify(res, function (key, value) { 
if (typeof value === 'object' && value !== null) { 
    if (cache.indexOf(value) !== -1) { 
    // Circular reference found, discard key 
    return; 
    } 
    // Store value in our collection 

    cache.push(value); 

    } 
    return value; 
}); 
}; 

var jsonObj = customStringify(res); 
var mainObj = JSON.parse(jsonObj); 
var leadObj = mainObj.socket.parser.incoming.body.entry[0].changes[0].value; 
console.log(leadObj); 


});