Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery JSON to string?

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?

like image 468
Incognito Avatar asked Aug 29 '10 00:08

Incognito


People also ask

How can I convert JSON to string?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

How can you parse JSON via jQuery?

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.

How does jQuery handle JSON data?

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.

How display JSON data in HTML using jQuery?

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.


2 Answers

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/

like image 181
Daniel R Avatar answered Sep 19 '22 02:09

Daniel R


I use

$.param(jsonObj) 

which gets me the string.

like image 42
jonathan Avatar answered Sep 20 '22 02:09

jonathan