第一种方式:
使用js函数eval();
testJson=eval(testJson);是错误的转换方式。
正确的转换方式需要加(): testJson = eval("(" + testJson + ")");
eval()的速度非常快,但是他可以编译以及执行任何javaScript程序,所以会存在安全问题。在使用eval()。来源必须是值得信赖的。需要使用更安全的json解析器。在服务器不严格的编码在json或者如果不严格验证的输入,就有可能提供无效的json或者载有危险的脚本,在eval()中执行脚本,释放恶意代码。
js代码:
第二种方式使用jquery.parseJSON()方法对json的格式要求比较高,必须符合json格式
jquery.parseJSON()
js:代码
================
. JSON.stringify(obj) : 将一个JSON对象转换成字符串
1 2 3 | var obj = [{ "href" : "baidu.com" , "text" : "test" , "orgId" :123, "dataType" : "curry" , "activeClass" : "haha" }]; JSON.stringify(obj); |
结果:
1 | "[{" href ":" baidu.com "," text ":" test "," orgId ":123," dataType ":" curry "," activeClass ":" haha "}]" |
. jQuery.parseJSON(jsonString) : 将格式完好的JSON字符串转为与之对应的JavaScript对象
1 2 3 | var str = '[{"href":"baidu.com","text":"test","orgId":123,"dataType":"curry","activeClass":"haha"}]' ; jQuery.parseJSON(str);
|