浅析Js(Jquery)中,字符串与JSON格式互相转换的示例(直接运行实例)
首先,准备新建一个js文件。以下是json2.js的内容,把内容拷到js文件中,以便调用:
. 代码如下:
/*
https://www.json.org/json2.js
public domain.
no warranty expressed or implied. use at your own risk.
see https://www.json.org/js.html
this code should be minified before deployment.
see https://javascript.crockford.com/jsmin.html
use your own copy. it is extremely unwise to load code from servers you do
not control.
this file creates a global json object containing two methods: stringify
and parse.
json.stringify(value, replacer, space)
value any javascript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. it can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. if it is omitted, the text will
be packed without extra whitespace. if it is a number,
it will specify the number of spaces to indent at each
level. if it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
this method produces a json text from a javascript value.
when an object value is found, if the object contains a tojson
method, its tojson method will be called and the result will be
stringified. a tojson method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. the tojson method
will be passed the key associated with the value, and this will be
bound to the value
for example, this would serialize dates as iso strings.
date.prototype.tojson = function (key) {
function f(n) {
// format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getutcfullyear() + '-' +
f(this.getutcmonth() + 1) + '-' +
f(this.getutcdate()) + 't' +
f(this.getutchours()) + ':' +
f(this.getutcminutes()) + ':' +
f(this.getutcseconds()) + 'z';
};
you can provide an optional replacer method. it will be passed the
&nbsnbsp; key and value of each member, with this bound to the containing
object. the value that is returned from your method will be
serialized. if your method returns undefined, then the member will
be excluded from the serialization.
if the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. it filters the results
such that only members with keys listed in the replacer array are
stringified.
values that do not have json representations, such as undefined or
functions, will not be serialized. such values in objects will be
dropped; in arrays they will be replaced with null. you can use
a replacer function to replace those with json values.
json.stringify(undefined) returns undefined.
the optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
if the space parameter is a non-empty string, then that string will
be used for indentation. if the space parameter is a number, then
the indentation will be that many spaces.
example:
text = json.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = json.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = json.stringify([new date()], function (key, value) {
return this[key] instanceof date ?
'date(' + this[key] + ')' : value;
});
// text is '["date(---current time---)"]'
json.parse(text, reviver)
this method parses a json text to produce an object or array.
it can throw a syntaxerror exception.
the optional reviver parameter is a function that can filter and
transform the results. it receives each of the keys and values,
and its return value is used instead of the original value.
if it returns what it received, then the structure is not modified.
if it returns undefined then the member is deleted.
example:
// parse the text. values that look like iso date strings will
// be converted to date objects.
mydata = json.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})t(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)z$/.exec(value);
if (a) {
return new date(date.utc(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
mydata = json.parse('["date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'date(' &&
value.slice(-1) === ')') {
d = new date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
this is a reference implementation. you are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, strict: false, regexp: false */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", json, "\\", apply,
call, charcodeat, getutcdate, getutcfullyear, getutchours,
getutcminutes, getutcmonth, getutcseconds, hasownproperty, join,
lastindex, length, parse, prototype, push, replace, slice, stringify,
test, tojson, tostring, valueof
*/
// create a json object only if one does not already exist. we create the
// methods in a closure to avoid creating global variables.
if (!this.json2)
{
this.json2 = {};
}
(function () {
"use strict";
function f(n) {
// format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof date.prototype.tojson !== 'function') {
date.prototype.tojson = function (key) {
return isfinite(this.valueof()) ?
this.getutcfullyear() + '-' +
f(this.getutcmonth() + 1) + '-' +
f(this.getutcdate()) + 't' +
f(this.getutchours()) + ':' +
f(this.getutcminutes()) + ':' +
f(this.getutcseconds()) + 'z' : null;
};
string.prototype.tojson =
number.prototype.tojson =
boolean.prototype.tojson = function (key) {
return this.valueof();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
escapable.lastindex = 0;
return escapable.test(string) ?
'"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charcodeat(0).tostring(16)).slice(-4);
}) + '"' :
'"' + string + '"';
}
function str(key, holder) {
var i, // the loop counter.
k, // the member key.
v, // the member value.
length,
mind = gap,
partial,
value = holder[key];
if (value && typeof value === 'object' &&
typeof value.tojson === 'function') {
value = value.tojson(key);
}
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
return isfinite(value) ? string(value) : 'null';
case 'boolean':
case 'null':
return string(value);
case 'object':
if (!value) {
return 'null';
}
gap += indent;
partial = [];
if (object.prototype.tostring.apply(value) === '[object array]') {
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
v = partial.length === 0 ? '[]' :
gap ? '[\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
k = rep[i];
if (typeof k === 'string') {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
for (k in value) {
if (object.hasownproperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
v = partial.length === 0 ? '{}' :
gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
mind + '}' : '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
if (typeof json2.stringify !== 'function') {
json2.stringify = function (value, replacer, space) {
var i;
gap = '';
indent = '';
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
} else if (typeof space === 'string') {
indent = space;
}
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new error('json2.stringify');
}
return str('', {'': value});
};
}
if (typeof json2.parse !== 'function') {
json2.parse = function (text, reviver) {
var j;
function walk(holder, key) {
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (object.hasownproperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
text = string(text);
cx.lastindex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charcodeat(0).tostring(16)).slice(-4);
});
}
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fa-f]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[ee][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
j = eval('(' + text + ')');
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
throw new syntaxerror('json2.parse');
};
}
}());
第二、调用页的内容
注意:调用js文件的路径需要自己调整,这点如果不会,那就别再继续看了。
. 代码如下:
<script src="../jquery/jquery-1.5.2.min.js" type="text/javascript"></script>
<script src="../json2.js" type="text/javascript"></script>
var a = '{ "name": "tom", "sex": "男", "age": "24" }'; // 用于组成json的字符串;
alert("用于组成json的字符串:【"+a+"】");
var b = json2.parse(a); // 把字符串a转换为json格式b
var c = json2.stringify(a); //把json格式b转换为字符串c
alert("转换后的字符串:【"+c+"】");