I have been confused over when to use these two parsing methods.
After I echo my json_encoded data and retrieve it back via ajax, I often run into confusion about when I should use JSON.stringify and JSON.parse.
I get [object,object]
in my console.log when parsed and a JavaScript object when stringified.
$.ajax({
url: "demo_test.txt",
success: function(data) {
console.log(JSON.stringify(data))
/* OR */
console.log(JSON.parse(data))
//this is what I am unsure about?
}
});
They are the inverse of each other.
JSON.stringify()
serializes a JS object into a JSON string, whereasJSON.parse()
will deserialize a JSON string into a JS object.JSON.stringify()
Converts an object into a string.JSON.parse()
Converts a JSON string into an object.JSON.stringify(obj [, replacer [, space]])
- Takes any serializable object and returns the JSON representation as a string.JSON.parse(string)
- Takes a well formed JSON string and returns the corresponding JavaScript object.Firstly,
JSON.stringify()
function converts a JavaScript value to a JavaScript Object Notation (JSON) string.JSON.parse()
function converts a JavaScript Object Notation (JSON) string into an object. For more information about these two functions, please refer to the following links.https://msdn.microsoft.com/library/cc836459(v=vs.94).aspx https://msdn.microsoft.com/library/cc836466(v=vs.94).aspx
Secondly, the following sample will be helpful for you to understand these two functions.
They are opposing each other.
JSON.Stringify()
converts JSON to string andJSON.Parse()
parses a string into JSON.The real confusion here is not about parse vs stringify, it's about the data type of the
data
parameter of the success callback.data
can be either the raw response, i.e a string, or it can be an JavaScript object, as per the documentation:And the dataType defaults to a setting of 'intelligent guess'