You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用API遇循环结构转JSON错误,CircularJSON返回null求解决

问题原因与解决方法

错误原因分析

  1. Circular structure to JSON 错误:你直接对Node.js http模块返回的response对象执行JSON.stringify(),但response是包含Socket等内部对象的流实例,这些内部对象存在循环引用(比如Socket与response互相引用),JSON序列化无法处理这种循环依赖,因此触发报错。
  2. CircularJSON处理后data.res为null:CircularJSON虽能处理循环引用,但你序列化的是整个response对象而非接口返回的纯数据body。response的很多内部属性无法被正常序列化/反序列化,最终导致解析后出现null。

正确解决步骤

核心:先收集接口返回的body数据,再处理

http模块的response是可读流,必须先拼接流数据得到接口返回的JSON字符串,再解析为纯数据对象,之后就能正常序列化:

const http = require('http');

http.get('http://dev3.dansmultipro.co.id/api/recruitment/positions.json', (res) => {
  let body = '';

  // 监听data事件,拼接流数据
  res.on('data', (chunk) => {
    body += chunk;
  });

  // 流结束后处理数据
  res.on('end', () => {
    try {
      // 将body解析为纯JSON对象
      const apiData = JSON.parse(body);
      // 此时可正常序列化
      const jsonString = JSON.stringify(apiData);
      console.log(jsonString);
    } catch (err) {
      console.error('JSON解析失败:', err);
    }
  });
}).on('error', (err) => {
  console.error('请求失败:', err);
});

若确实需处理循环引用对象

如果业务中遇到其他含循环引用的对象,可通过以下方式处理:

  • 原生replacer函数:自定义序列化规则,跳过循环引用
function circularReplacer(key, value) {
  if (typeof value === 'object' && value !== null) {
    if (this.seen.has(value)) return '[Circular]';
    this.seen.add(value);
  }
  return value;
}

// 使用示例
const jsonStr = JSON.stringify(yourCircularObj, circularReplacer.bind({ seen: new WeakSet() }));
  • 使用现代库flatted:替代过时的CircularJSON,序列化/反序列化更可靠
npm install flatted
const flatted = require('flatted');
const jsonStr = flatted.stringify(yourCircularObj);
const parsedData = flatted.parse(jsonStr);

内容的提问来源于stack exchange,提问作者Daniel Eka Putra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:05:10