1

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.

1
  • 2
    yes, overwriting the global toString is sure to break all kinds of things... Commented May 5, 2014 at 8:39

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks i found the answer on the page you referred. No idea why i missed it in fist place
0

Try using toJSON

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

this may solve your problem

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.