LNT
LNT

Reputation: 916

Stringify function in JavaScript

What I am thinking of writing is something like this.

Object.prototype.toString = function(){
var ret = '{';
for(var i in this){
    if(this[i].toString)
    ret = ret + ( '"'+i+'":' + this[i].toString())
}
ret=ret+'}'; return ret;
}

I will do this for Number and other known dataTypes.

I have seen many utils.stringify fucntions available , along with JSON.stringify, what all these libs are doing is that, they are checking type of object and based on that they concatenating strings to create Json. which is ok, I cant use those fucntions because I want to use something like this: -

function subMap(){
    this.data = { a  : 'A', b : 'B'}
    this.toString = function(){
         return  this.data.toString()
    }
}
utils.parse(({
   x : new subMap()
}).toString())

which should return something like this

"{"x":{"a":"A","b":"B"}}"

Basically I want to have way where I can decide how to represent StringFormat(JSON) for any ObjectType, whenever I add a new DataType.

But looking at all the available libs I see no one is doing this way(defining toString function), which i m thinking is better way. Is there any drawback or something JavaScript is using it internally to do something which will break something or any other reason they are not using it?

Edit

I found the answer. at link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

function subMap(){
    this.data = { a  : 'A', b : 'B'}
    this.toJSON = function(){
         return this.data;
    }
}

should work as I expect.

Upvotes: 1

Views: 609

Answers (2)

Armann Shorya
Armann Shorya

Reputation: 11

Try using toJSON

function subMap(){
    this.data = { a  : 'A', b : 'B'}
    this.toJSON = function(){
         return this.data;
    }
}

this may solve your problem

Upvotes: 0

thebjorn
thebjorn

Reputation: 27311

You can use the second argument to JSON.stringify(value, replacer, space) to do this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Upvotes: 1

Related Questions