Monday 27 November 2017

javascript - jquery json to string?

itemprop="text">

Instead of going from 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?



Answer




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: href="https://github.com/douglascrockford/JSON-js"
rel="noreferrer">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: href="http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/"
rel="noreferrer">http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...