skip to Main Content

I’m testing facebook leadgen api using a Node JS app.
Using Facebook Test tool, I’m getting a response from Facebook. When I tried JSON.stringify() I got Converting circular structure to JSON error. How do I get the values for the field leadgen.

Test Data from facebook:

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

I tried printing the response using log. But the response looked something like this. I couldn’t understand how to parse it.

    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': [......

2

Answers


  1. Chosen as BEST ANSWER

    Finally after lot of iterations the below code solved my problem:

     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);
    
    
    });
    

  2. You can use this custom stringify function, which can handle circular dependencies. This is standard, I stole it from someone else.

    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;
      });
    };
    

    Although if you are trying parse a response, you may wish to call JSON.parse instead of JSON.stringify.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search