json2的使用

 

JSON2的使用方法心得


var myJSONObject = {"bindings": [ 
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}, 
        {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"}, 
        {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"} 
    ] 
};

这个例子中,创建了一个对象,它只包含一个成员“bindings”。“bindings”是一个包含了3个对象的数组,而这每个对象都有"ircEvent"、"method"和"regex"3个成员。

这些成员可以用“.”或subscript 操作得到。

如:myJSONObject.bindings[0].method    // "newURI"
    myJSONObject.bindings[1].deleteURI    // "newURI"
    
//声明字符串,可对比一下json文本与我们正常文本的区别 
var normalstring='[{persons:[{name:"jordan",sex:"m",age:"40"}, {name:"bryant",sex:"m",age:"28"}, {name:"McGrady",sex:"m",age:"27"} ]}]'; 
var jsontext='[{"persons":[{"name":"jordan","sex":"m","age":"40"}, {"name":"bryant","sex":"m","age":"28"}, {"name":"McGrady","sex":"m","age":"27"} ]}]';

我们可以使用eval()函数调用JavaScript的编译器把JSON文本转变成对象。因为JSON是JavaScript的一个确切的子集,编译器可以正确地解析JSON文本,然后生成一个对象结构。

//调用eval函数转换为json对象, 
var myE = eval(normalstring);

//将json对象转换为字符串 
var text = JSON.stringify(myE);

//对比转换后的json文本与声明的文本区别 
document.writeln('转换后的json文本:'+text+'<br><br>声明的json格式文本 '+jsontext+'<br><br>声明的普通格式文本 '+normalstring+'<br><br>');

结果如下:

转换后的json文本:[{"persons":[{"name":"jordan","sex":"m","age":"40"},{"name":"bryant","sex":"m","age":"28"},{"name":"McGrady","sex":"m","age":"27"}]}]

声明的json格式文本 [{"persons":[{"name":"jordan","sex":"m","age":"40"},{"name":"bryant","sex":"m","age":"28"},{"name":"McGrady","sex":"m","age":"27"}]}]

声明的普通格式文本 [{persons:[{name:"jordan",sex:"m",age:"40"}, {name:"bryant",sex:"m",age:"28"}, {name:"McGrady",sex:"m",age:"27"} ]}]

小结:转换后的json文本和声明的json格式文本内容是相同的。

//当安全比较重要的时候使用JSON解析就好一些。JSON解析只会识别JSON文本并且它更安全,下面调用json的parse函数对文本数据转换生成json数据结构 
var myData = JSON.parse(jsontext);

完整的文件如下(区别:myJSONObject,jsontext,normalstring的不同):
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
   <script type="text/javascript" src="js/json2.js"></script>
</head>

<body>
   <script>
    var normalstring='[{persons:[{name:"jordan",sex:"m",age:"40"}, {name:"bryant",sex:"m",age:"28"}, {name:"McGrady",sex:"m",age:"27"} ]}]'; 
    var jsontext='[{"persons":[{"name":"jordan","sex":"m","age":"40"}, {"name":"bryant","sex":"m","age":"28"}, {"name":"McGrady","sex":"m","age":"27"} ]}]';
    var myJSONObject = {"bindings": [ 
          {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}, 
          {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"}, 
          {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"} 
       ] 
    }; 
   
    //调用eval函数转换为json对象, 
    var myE = eval(normalstring); 
   
    //将json对象转换为字符串 
    var text = JSON.stringify(myE); 
   
    //对比转换后的json文本与声明的文本区别 
    document.writeln('转换后的json文本:'+text+'<br><br>声明的json格式文本 '+jsontext+'<br><br>声明的普通格式文本 '+normalstring+'<br><br>');
  
    //JSON解析
    var myData = JSON.parse(jsontext);
   </script>
</body>
</html>


4.)示例演示二:

//下面是对json对象的增删查改操作
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
   <script type="text/javascript" src="js/json2.js"></script>
</head>

<body>
   <script>
    //声明json对象
    var jsonObj2={persons:[
     {name:"jordan",sex:"m",age:"40"}, 
     {name:"bryant",sex:"m",age:"28"}, 
     {name:"McGrady",sex:"m",age:"27"} 
    ]};
    var persons=jsonObj2.persons; 
    var str="";
    var person={name:"yaoMing",sex:"m",age:"26"}; 
   
    //以下为json对象的操作,去掉注释可以查看操作结果 
    jsonObj2.persons.push(person);//数组最后加一条记录 
    jsonObj2.persons.pop();//删除最后一项 
    jsonObj2.persons.shift();//删除第一项 
    jsonObj2.persons.unshift(person);//数组最前面加一条记录 只要适合Javascript的方法都是可以用在JSON对象的数组中的!所以还有另外的方法splice( )进行crud操作! //删除 
    jsonObj2.persons.splice(0,2);//开始位置,删除个数 
   
    //替换不删除 
    var self={name:"tom",sex:"m",age:"24"}; 
    var brother={name:"Mike",sex:"m",age:"29"}; 
    jsonObj2.persons.splice(1,0,self,brother,self);//开始位置,删除个数,插入对象 
   
    //替换并删除 
    jsonObj2.persons.splice(0,1,self,brother);//开始位置,删除个数,插入对象
   
    for(var i=0;i<persons.length;i++){ 
     var cur_person=persons[i]; 
     str+=cur_person.name+"'sex is "+cur_person.sex+" and age is "+cur_person.age+"<br><br>";
    } 
    document.writeln(str); 
    //转换为json文本 
    var myjsonobj = JSON.stringify(jsonObj2); 
    document.writeln(myjsonobj);

    document.writeln(persons.length);

   </script>
</body>
</html>

     

    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 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.
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值