There are lot of people still confused about Javascript Object versus and JSON.
both are same?
Answer is No . There is a difference between two
Look at the below sample code , both objects are valid javascript object literal.
var employeeObject1 = {
firstName: "Jameel",
lastName: "Moideen"
}
var employeeObject2 = {
"firstName": "Jameel",
"lastName": "Moideen"
}
Then what is the difference between JSON?
Answer is very simple. JSON have very strict rule , the property name should enclose with quotes.In the above example employeeObject2 is valid JSON.
Valid JSON
{
“firstName”: “Jameel”,
“lastName”: “Moideen”
}
InValid JSON
{
firstName: “Jameel”,
lastName: “Moideen”
}
There are some built in function in javascript to convert an array in to JSON , which can use from object to Valid JSON before you send it across the wire.
JSON.stringfy() – Convert an object to valid JSON
Example
JSON.stringify(employeeObject1)
“{“firstName”:”Jameel”,”lastName”:”Moideen”}”
JSON.parse() – Convert a string to Javascript Object
JSON.parse('{"firstName":"Jameel","lastName":"Moideen"}')
{firstName: “Jameel”, lastName: “Moideen”}