illusion
illusion

Reputation: 1301

near-api-js, view contract method call gives: TypeError: JSON.stringify cannot serialize cyclic structures

Whenever I am calling my contract view method using near-cli, it is working fine, the terminal outputs the result correctly in JSON format.

But when I call the same method using near-api-js method in my angular project, it gives an error:

Error: Uncaught (in promise): TypeError: JSON.stringify cannot serialize cyclic structures.

Output from near-cli for reference and also the expected output when I call the same method via near-api-js:

{
  files: [
    {
      owner: 'some string',
      key: 'some string',
      cid: 'some string'
    }
  ],
  length: 1
}

What may be the cause of this and what's the solution?

Upvotes: 2

Views: 222

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76787

Circular reference example:

var circularReference = {otherData: 123};
circularReference.myself = circularReference;
JSON.stringify(circularReference);

Explanation: circularReference refers to itself via cirularReference.myself.

Mozilla's website has a nice example of how the circular reference can be found and removed:

const getCircularReplacer = () => {
  const seen = new WeakSet();
  return (key, value) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) {
        return;
      }
      seen.add(value);
    }
    return value;
  };
};

JSON.stringify(circularReference, getCircularReplacer());
// {"otherData":123}

Instead of removing the circular reference, you can modify it.

However, this is symptomatic treatment. The very best would be to find out why the circular reference appeared in the first place and if that's caused by a bug, then fix it.

Upvotes: 2

Related Questions