Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify turned the value array into a string

I have a JS object

{
    aString:[aNumber, aURL]
}

JSON.stringify() returns

{
    "aString":"[number, \"aURL\"]"
}

I thought that valid JSON can have arrays as values. Can I have stringify return the JSON string without converting the array into a string? Basically I need turn the whole JS object straight into a string, without any modification.

Is there a better way to do this? I've been looking around but everyone suggests using JSON.stringify if I want an object to string, and no one has raised this problem.

EDIT: Thanks for the quick responses. Here is how I created my JS object, please let me know if I messed up and how!

cookie = {};
// productURL is a string, timer is a number, imageSrc is a URL string
cookie[productURL] = [timer, imageSrc];
// then, I just stringified cookie
newCookie = JSON.stringify(cookie);

If it is also relevant, I am setting an actual cookie's value as the resulting JSON string, in order to access it in another set of functions. Setting the cookie's value does do some URI encoding of its own, but I've actually been grabbing the value of newCookie in the Chrome console as well and it also returns the Array as a string.

like image 949
user4694769 Avatar asked Apr 14 '15 21:04

user4694769


1 Answers

If an object you're trying to stringify has a toJSON function, that will be called by JSON.stringify. Most likely you have an external library that's adding Array.prototype.toJSON.

For example, an old version (1.6) of Prototype JS will "conveniently" add that for you.

Prototype 1.6.1:

alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.6.1/prototype.min.js"></script>

Whereas a newer version will not.

Prototype 1.7.2:

alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.min.js"></script>

You could try deleting Array.prototype.toJSON just to see if that's what's causing the problem. If it is, you might want to look into upgrading/deprecating any libraries in your code that do weird things like that.

Prototype 1.6.1 (after deleting toJSON)

delete Array.prototype.toJSON;
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.6.1/prototype.min.js"></script>
like image 173
redbmk Avatar answered Sep 18 '22 01:09

redbmk