json对象的操作,json工具

  项目中经常用到json,现在把写了几个js函数,用来获取json对象或者json字符串的长度,以及获取其的key值,value值,并且返回。

这样以后可以直接拿来用,可以省去不少麻烦,也方便以后查看。

 1 /**
 2  * 检验传入的对象是否为json对象或者json字符串, 符合条件则返回json对象,否则返回false
 3  * 不能够传入字符串"weiyl","abcd"非json字符串,否则会报错。
 4  * @param json
 5  * @returns
 6  */
 7 function toJson(json) {
 8     var type = typeof json;
 9     /**
10      * 防止传入的字符串是null,undefined或者''空字符串,所以判断的时候 
11      * 用type=="string"与上json本身
12      */
13     if (type == "string" && json) {
14         return JSON.parse(json);
15     } else if (type == "object") {
16         return json;
17     } else {
18         alert('你传入的参数' + json + ',不是json对象或者json格式的字符串');
19         return false;
20     }
21 }
22 /**
23  * 使用typeof操作符 对一个值使用typeof操作符可能返回下列某个字符串:
24  * 
25  * 1):undefined——如果这个值未定义
26  * 
27  * 2):boolean——如果这个值是布尔值
28  * 
29  * 3):string——如果这个值是字符串
30  * 
31  * 4):number——如果这个值是数值
32  * 
33  * 5):object——如果这个值是对象或null
34  * 
35  * 6):function——如果这个值是函数 传入一个json对象,或者json格式
36  * 的字符串,返回这个json对象的长度, 否则,返回 -1
37  * 
38  * @param jsonObj
39  * @returns {Number}
40  */
41 function getJsonLen(jsonObj) {
42     jsonObj = toJson(jsonObj);
43     var type = typeof jsonObj;
44     if (type == "boolean" || type == undefined || type == "number"
45             || type == "function") {
46         return -1;
47     }
48     var len = 0;
49     for ( var item in jsonObj) {
50         len++;
51     }
52     return len;
53 }
54 
55 /**
56  * /** 传入一个json字符串或者json对象, 获取所有key值,并且
57  * 以数组形式返回, 如果传入的不是json字符串或者json对象, 就返回-1
58  * 
59  * @param JsonObj
60  * @returns {Array}
61  */
62 function getJsonKey(JsonObj) {
63     var len = getJsonLen(JsonObj);
64     if (len == -1) {
65         return -1;
66     }
67     var array = [];
68     /*
69      * 因为在getJsonLen()方法中对传入的对象做了 判断,所以这里
70      * 就不用再判断是否为json或者json字符串了
71      */
72     for ( var item in JsonObj) {
73         array.push(item);
74     }
75     return array;
76 }
77 /**
78  * 传入一个json字符串或者json对象, 获取所有value值,并且以
79  * 数组形式返回, 如果传入的不是json字符串或者json对象, 就返回-1
80  * 
81  * @param JsonObj
82  * @returns {Array}
83  */
84 function getJsonValue(JsonObj) {
85     var len = getJsonLen(JsonObj);
86     if (len == -1) {
87         return -1;
88     }
89     var array = [];
90     /*
91      * 因为在getJsonLen()方法中对传入的对象做了 判断,所以
92      * 这里就不用再判断是否为json或者json字符串了
93      */
94     for ( var item in JsonObj) {
95         array.push(JsonObj[item]);
96     }
97     return array;
98 }

以上几个方法可以用来对json对象或者json字符串做一些常见的操作,这是下载链接myJsonUtil.js

原文地址:https://www.cnblogs.com/Sunnor/p/5174251.html