将javascript对象转换为json对象[重复]
Posted
技术标签:
【中文标题】将javascript对象转换为json对象[重复]【英文标题】:Converting the javascript object to json object [duplicate] 【发布时间】:2015-01-02 06:36:36 【问题描述】:我正在创建一个 logMessage 对象。
logMessage = function (msg, severity, vendorId, userName, actionPerformed, priority, traceId, dataSent)
this.message = msg;
this.severity = severity;
this.vendorId = vendorId;
this.userName = userName;
this.actionPerformed = actionPerformed;
this.priority = priority;
this.traceId = traceId;
this.dataSent = dataSent;
;
var msg = new logMessage(err, "High", "none", qry.username, "Error on login call: /req/login", "high", "", qry);
Utility.writeToLoggly(msg);
err ,qry
是 json 对象;如何将 msg 对象转换为 json 对象?
我将msg
对象发送到loggly
以进行日志管理。如果我能将格式正确的 json 对象发送到 loggly
,那就太好了。
【问题讨论】:
JSON.stringify(msg)
注意:按照约定,JS“类”以大写字母开头。
附注谷歌搜索“javascript json 输出”很容易产生几个带有正确答案的页面。
顺便说一句:没有 JSON object 这样的东西。 JSON 是一个字符串。
【参考方案1】:
logMessage = function (msg, severity, vendorId, userName, actionPerformed, priority, traceId, dataSent)
this.message = msg;
this.severity = severity;
this.vendorId = vendorId;
this.userName = userName;
this.actionPerformed = actionPerformed;
this.priority = priority;
this.traceId = traceId;
this.dataSent = dataSent;
;
var msg = new logMessage(err, "High", "none", qry.username, "Error on login call: /req/login", "high", "", qry);
Utility.writeToLoggly(JSON.stringify(msg));
【讨论】:
【参考方案2】:您可以使用 JSON.stringify() 函数,因此只需添加到您的代码中:
Utility.writeToLoggly(JSON.stringify(msg));
【讨论】:
以上是关于将javascript对象转换为json对象[重复]的主要内容,如果未能解决你的问题,请参考以下文章
无法将 JavaScript window.screen 对象转换为字符串 [重复]