0

Before I go and create this myself, I thought I'd see if anyone knows a library that does this.

I'm looking for a function that will take something in Javascript, be it an array, an associative array, a number, or even a string, and convert it to something that looks like it. For example:

toString([1,2,3]) === '[1, 2, 3]'
toString([[1,2], [2,4], [3,6]]) === '[[1,2], [2,4], [3,6]]'
toString(23) === '23'
toString('hello world') === 'hello world'
toString({'one': 1, 'two': 2, 'three': 3}) === "{'one': 1, 'two': 2, 'three': 3}"
4
  • 9
    Mmm... JSON.stringify should come close I think Commented Jan 29, 2011 at 23:25
  • 2
    Basically you want to create JSON :) json.org Commented Jan 29, 2011 at 23:27
  • 1
    Is the 'hello world' example correct or did you forget to add quotes? If this is the case then JSON.stringify is what you're searching for. Commented Jan 29, 2011 at 23:29
  • @Jeff: do you need any more help here? Commented Feb 1, 2011 at 13:44

1 Answer 1

4

As mentioned in the comments (and I'm surprised nobody actually posted it as an answer), JSON.stringify() is the method that you're looking for. It's supported natively in most browsers these days, but you can also implement it in the browsers that don't support it using json2.js.

Working demo: http://jsfiddle.net/AndyE/WXfzJ/

The only exception is function objects, which won't be stringified by JSON. However, Function.prototype.toString will return a re-parseable string representation of the function, although you should be aware that white-space and comments may be stripped depending on the browser:

function moo() {
    alert('cow says moo!');
}

alert(moo.toString());
Sign up to request clarification or add additional context in comments.

7 Comments

Be wary of JSON.stringify("foo") === ""foo""
Mention the non-standard .toString on functions for printing out source code.
@Raynos: was just in the process of doing so :-) by the way, it is part of the spec, except that it is defined that the resulting source code can be implementation dependant. This means, for user code, white-space and comments may be stripped.
@AndyE I swear IE just prints [object Function] or something for .toString
@Raynos: nope, that would be the result of Object.prototype.toString.apply(fn).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.