I'm doing a 'manual' run through my javascript class' properties in order to form JSON, as seen below. It feels clumsy and I would to learn how to do this automatically, so I wouldn't have to mess with the 'toJson' function if I add or remove any properties, for example.
Can a helpful mind point me in the right direction on how to adapt the below 'toJson' function towards this purpose?
Many thanks in advance.
/* Using Simple JavaScript Inheritance * By John Resig http://ejohn.org/ * MIT Licensed.*/ var LogEntry = Class.extend({ init: function (_conferenceId, _tokenId, _logType, _logValue) { this.dato = new Date(); this.logValue = _logValue; this.logType = _logType; this.conferenceId = _conferenceId; this.tokenId = _tokenId; }, toJson: function () { // ? var jsonStringBuilder = '{ '; jsonStringBuilder += '"dato": ' + this.dato.toString() + ','; jsonStringBuilder += '"conferenceId": ' + this.conferenceId + ','; if (this.tokenId== null) { jsonStringBuilder += '"tokenId":null,'; } else { jsonStringBuilder += '"tokenId": ' + _tokenId + ','; } jsonStringBuilder += '"logValue": ' + this.logValue + ','; jsonStringBuilder += '"logType": ' + this.logType; jsonStringBuilder += '}'; return jsonStringBuilder; } });
Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
To fix this, you can use the JSON. stringify() method to change the object into a string that can be popped up in the browser using the alert() method.
JSON.stringify
is the function you're looking for.
Some very old browsers do not natively provide the JSON
object, but you can use a shim library for those browsers.
I think you're looking for JSON.stringify()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With