Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m just wondering about \"stringify\" vs \"serialize\". To me they\'re the sam

ID: 646303 • Letter: I

Question

I'm just wondering about "stringify" vs "serialize". To me they're the same thing (though I could be wrong), but in my past experience (mostly with asp.net) I use Serialize() and never use Stringify().

I know I can create a simple alias in Javascript,

// either
JSON.serialize = function(input) {
    return JSON.stringify(input);
};

// or
JSON.serialize = JSON.stringify;
http://jsfiddle.net/HKKUb/

but I'm just wondering about the difference between the two and why stringify was chosen.

for comparison purpose, here's how you serialize XML to a String in C#

public static string SerializeObject<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
    StringWriter textWriter = new StringWriter();

    xmlSerializer.Serialize(textWriter, toSerialize);
    return textWriter.ToString();
}

Explanation / Answer

Take a closer look at the two comments you've put onto the question:

I suppose after re-reading my question, I'm seeing that in my C# example, I'm serializing the XML and THEN converting the serialized object ToString();. There inlies the rub.

and

I guess for continuity, it would be better (for me) to have a method that looks like this... JSON.serialize(obj).toString(); or jsonObject().toString();... this way it would look much like my C#... but now I'm over complicating it.

Now remember that in Javascript, an object is a hash (rather, if using Prototype or another framework, it should be qualified as a "special kind of hash" - but the simple form works for this example):

var obj = {
foo: 1,
bar: function() { console.log(this.foo); }
}
obj.foo; // 1
obj.bar; // function reference
obj.bar(); // function call
obj['foo']; // 1
obj['bar']; // function reference
obj['bar'](); // function call
The only reason a serialize() might be necessary in Javascript is to cut out the functions, references to other objects, etc.

So, to go back to your C# example - we've just cut out .Serialize() as unnecessary. An object is a hash, it's already serialized, further "serialization" would have to be done manually in your own code anyway. All that leaves you is .ToString().

Does .stringify() make more sense now?

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote