一、字符串转json:
代码:
/*@desc:字符串转json函数@author <lee> [<complet@163.com>]@param str 字符串@return json json对象*/function strtojson(str){var arr = str.split('&')var json = {}for(var i in arr){ var k = arr[i].split('=')[0] var v = arr[i].split('=')[1] json[k] = v}console.log(json)}
测试:
var str = 'name=lee&sex=male'var ret = strtojson(str)console.log(ret)
输出:
{ name: 'lee', sex: 'male' }
二、json转字符串:
代码:
/*@desc:json转字符串函数@author <lee> [<complet@163.com>]@param json json对象@return str 字符串*/function jsontostr(json){var arr = new Array()for(var k in json){ var v = json[k] var val = k+'='+v arr.push(val)}var str = arr.join('&')return str}
测试:
var json = {name:'lee',sex:'male'}var ret = jsontostr(json)console.log(ret)
输出:
name=lee&sex=male