You are here
javascript json 添加 修改 删除 的操作
星期四, 2015-10-22 14:04 — shiping1
Java代码 - <html>
- <script>
-
-
- function $parseJson(str){
- try{
- eval('var obj='+str);
- return obj;
- }catch(e){
- return null;
- }
- }
-
- function $ArrayToString(arr)
- {
- var separator = ",";
- for(var i=0;i<arr.length;i++){
- arr[i]=$toJsonString(arr[i]);
- }
- return arr.join(separator);
- }
-
- function $toJsonString(obj){
- var isArray = obj instanceof Array;
- var r = [];
- for(var i in obj){
- var value = obj[i];
- if(typeof value == 'string'){
- value = '"' + value + '"';
- }else if(value != null && typeof value == 'object'){
- value = $toJsonString(value);
- }
- r.push((isArray?'':i+':')+value);
- }
- if(isArray){
- return '['+r.join(',')+']';
- }else{
- return '{'+r.join(',')+'}';
- }
- }
-
-
-
-
-
-
-
-
- var addjson1={"901":{}};
-
- function addjson(jsonname,element,attribute){
- var jsonString=$toJsonString(jsonname);
- var jsonString = jsonString.substring(0,jsonString.length-1);
- var jsonArr=","+element+":"+attribute+"}";
- var jsonString=jsonString.concat(jsonArr);
- alert(jsonString);
- jsonname=$parseJson(jsonString);
- alert(jsonname[element]);
- }
-
-
-
- addjson(addjson1,902,"'蒋佳良'");
- addjson(addjson1,903,"{name:'蒋佳良'}");
- addjson(addjson1,904,"[{name:'蒋佳良'},{name:'蒋佳良'}]");
-
-
-
-
-
- var addjson2=[{name:"蒋佳良"},{name:"蒋佳良"}];
-
-
-
-
-
-
- addjson2.splice(2,0,{name:"你把我推进去,并排在第3个"});
- alert(addjson2[2].name);
-
-
- addjson2.push({name:"你把我推进去,但是排在最后面的"});
- alert(addjson2[addjson2.length-1].name);
-
-
-
-
-
-
-
- var uptatejson=[{name:"蒋佳良"},{name:"蒋佳良"}];
- uptatejson[0].name="你把我修改了";
- alert(uptatejson[0].name);
-
-
-
- var json1={name:"蒋佳良"};
- alert(json1.name);
- delete json1.name;
- alert(json1.name);
-
- var json2=[{name:"蒋佳良"},{name:"蒋佳良"}];
- alert(json2[1].name);
- delete json2[1].name;
- alert(json2[1].name);
- </script>
- </html>