Examples of mutual conversion between strings and JSON formats in Js (Jquery) (directly running instances) _ jquery

Source: Internet
Author: User
Tags tojson hasownproperty
In the past few days, I met the json format in the JS and Jquey environments and needed to switch between them. I checked it online. Most of them were out of arms and legs. Maybe I am a cainiao, after the test is successful, let's take an instance for beginners. First, create a new js file. The following is the content of JSON2.js. Copy the content to the js file for calling:

The Code is as follows:


/*
Http://www.JSON.org/json2.js
Public Domain.
No warranty expressed or implied. use at your own risk.
See http://www.JSON.org/js.html
This code shoshould be minified before deployment.
See http://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
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
Value represented by the name/value pair that shocould be serialized,
Or undefined if nothing shocould 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 wowould 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
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
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 specified 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 "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 returns es each of the keys and values,
And its return value is used instead of the original value.
If it returns what it has ED, 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;
If (typeof value = 'string '){
A =
/^ (\ D {4})-(\ d {2})-(\ d {2}) T (\ d {2}) :( \ d {2 }) :( \ d {2 }(? : \. \ D *)?) Z $/. exec (value );
If (){
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 edevil: 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
// 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-\ signature \ 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 (){
Var c = meta [a];
Return typeof c = 'string '? C:
'\ U' + ('000000' + 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 (){
Return '\ U' +
('100' + 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 ');
};
}
}());


2. Call page content
Note: You need to adjust the path of the js file to be called. If this is not the case, stop reading it.

The Code is as follows:


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.