简体   繁体   中英

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;
        }
});

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.

我想你正在寻找JSON.stringify()

You can use stringify if you want. Javascript is also really freakin' cool and allows you to pass context abstracts so you really don't need to define class members as you are. I don't know what your end goal is but check this:

function foo(context) { 
    dosomething(context.bar);
}

You can dynamically add an arbitrary number of members with simple declarations, making context a JSON object inherently like this:

context.bar = "hello world";

This way when you pass 'context' to the server, there's no real need to "stringify" it (assuming your backend framework has some sort of JSON parsing that is).

Edit: I got a little off topic, I just hate seeing long strings of params in JS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM