Convert Object to JSON string

JqueryJson

Jquery Problem Overview


jQuery.parseJSON('{"name":"John"}') converts string representation to object but I want the reverse. Object is to be converted to JSON string I got a link http://www.devcurry.com/2010/03/convert-javascript-object-to-json.html but it need to have json2.js do jQuery has a native method to do this?

Jquery Solutions


Solution 1 - Jquery

jQuery does only make some regexp checking before calling the native browser method window.JSON.parse(). If that is not available, it uses eval() or more exactly new Function() to create a Javascript object.

The opposite of JSON.parse() is JSON.stringify() which serializes a Javascript object into a string. jQuery does not have functionality of its own for that, you have to use the browser built-in version or json2.js from http://www.json.org

JSON.stringify() is available in all major browsers, but to be compatible with older browsers you still need that fallback.

Solution 2 - Jquery

Also useful is Object.toSource() for debugging purposes, where you want to show the object and its properties for debugging purposes. This is a generic Javascript (not jQuery) function, however it only works in "modern" browsers.

Solution 3 - Jquery

Convert JavaScript object to json data

$("form").submit(function(event){
  event.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvertedData = JSON.stringify(formData);  // Convert to json
  consol.log(jsonConvertedData);
});

You can validate json data using http://jsonlint.com

Solution 4 - Jquery

You can use the excellent jquery-Json plugin:

http://code.google.com/p/jquery-json/

Makes it easy to convert to and from Json objects.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKuttan SujithView Question on Stackoverflow
Solution 1 - JqueryjAndyView Answer on Stackoverflow
Solution 2 - JqueryExcaliburView Answer on Stackoverflow
Solution 3 - JquerySubroto BiswasView Answer on Stackoverflow
Solution 4 - JqueryGeorge FilippakosView Answer on Stackoverflow