将自定义javascript对象转换为json
Convert custom javascript object to json
我试图将javascript中的自定义对象转换为json字符串,但我一直收到循环引用错误。有没有一种方法可以使用JSON.stringify,或者我必须自己手动创建字符串?
这是我的代码:
function configuration(comments, instances, connections)
{
this.comments = comments;
this.instances = instances;
this.connections = connections;
return this;
}
function instance(id, type)
{
this.id = id;
this.type = type;
return this;
}
function connection(from, to)
{
this.from = from;
this.to = to;
return this;
}
function from(id, property, index)
{
this.id = id;
this.property = property;
this.index = index;
return this;
}
function to(id, property, index)
{
this.id = id;
this.property = property;
this.index = index;
return this;
}
var comments = "this is a test comment";
var instances = [];
var connections = [];
connections.push(connection(from("34hvd","inputs", 0), to("dheb3", "outputs", 0)));
instances.push(instance("34vd", "tee"));
instances.push(instance("dheb2", "average"));
var config = configuration(comments, instances, connections);
JSON.stringify(config);
正如您所看到的,我正在尝试字符串化配置对象,它包含注释(字符串)、实例(实例对象数组)和连接(连接对象数组)。
如果有更好的方法,请告诉我。感谢
如果在调用函数时不使用new
,则返回的this
将引用window
,即创建循环引用的内容。
这将工作
connections.push(new connection(new from("34hvd","inputs", 0), new to("dheb3", "outputs", 0)));
instances.push(new instance("34vd", "tee"));
instances.push(new instance("dheb2", "average"));
var config = new configuration(comments, instances, connections);
console.log(config)
相关文章:
- DOM事件通过JSON转换为java
- 将日期时间从json转换为可读格式
- 如何将JSON转换为HTML下拉菜单
- 将JSON转换为放入Sdcard中的CSV文件
- 将JSON转换为typescript中的字符串数组
- 无法在Angular.js中将JSON转换为数组
- 使用jquery将json转换为数组
- 是否有将基于字符串的JSON转换为Mongoose Schema对象实例的本地功能
- 用D3js将JSON转换为SVG平面图
- 数组json转换为数组json
- 将JSON转换为特定的字符串格式
- 使用AJAX将JSON转换为PHP
- 使用JQuery将JSON转换为数组
- 使用 PHP 将 JSON 转换为 JavaScript
- 将 JavaScript 程序从 JSON 转换为 XML
- 将 JSON 转换为 CSV 格式
- 将 json 转换为 html 表的 JavaScript 不起作用
- 使用 D3 将分层 JSON 转换为 HTML
- 余烬原始 JSON 转换不起作用,但例外
- 如何将JSON转换为角度的HTML