Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to JSONify a javascript object's properties

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;         } }); 
like image 618
Morten Nørgaard Avatar asked Oct 07 '13 20:10

Morten Nørgaard


People also ask

How do you use Jsonify in JavaScript?

Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

What is Stringify in JavaScript?

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.

Which JavaScript method converts JSON to a JavaScript value?

parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

How do you fix an object object in HTML?

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.


2 Answers

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.

like image 55
josh3736 Avatar answered Sep 27 '22 21:09

josh3736


I think you're looking for JSON.stringify().

like image 35
GolezTrol Avatar answered Sep 27 '22 23:09

GolezTrol