Instead of going JSON a json string and using $.parseJSON, I need to take my object and store it in a variable as string representing JSON.
(A library I'm dealing with expects a malformed JSON type so I need to mess around with it to get it to work.)
What's the best way to do this?
Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
JQuery | parseJSON() method This parseJSON() Method in jQuery takes a well-formed JSON string and returns the resulting JavaScript value. Parameters: The parseXML() method accepts only one parameter that is mentioned above and described below: json: This parameter is the well-formed JSON string to be parsed.
To load JSON data using jQuery, use the getJSON() and ajax() method. The jQuery. getJSON( ) method loads JSON data from the server using a GET HTTP request. data − This optional parameter represents key/value pairs that will be sent to the server.
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
Edit: You should use the json2.js library from Douglas Crockford instead of implementing the code below. It provides some extra features and better/older browser support.
Grab the json2.js file from: https://github.com/douglascrockford/JSON-js
// implement JSON.stringify serialization JSON.stringify = JSON.stringify || function (obj) { var t = typeof (obj); if (t != "object" || obj === null) { // simple data type if (t == "string") obj = '"'+obj+'"'; return String(obj); } else { // recurse array or object var n, v, json = [], arr = (obj && obj.constructor == Array); for (n in obj) { v = obj[n]; t = typeof(v); if (t == "string") v = '"'+v+'"'; else if (t == "object" && v !== null) v = JSON.stringify(v); json.push((arr ? "" : '"' + n + '":') + String(v)); } return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}"); } }; var tmp = {one: 1, two: "2"}; JSON.stringify(tmp); // '{"one":1,"two":"2"}'
Code from: http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/
I use
$.param(jsonObj)
which gets me the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With