JSON轉Object官方原文:
地址:http://www.json.org/js.html
To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.
var myObject = eval('(' + myJSONtext + ')');
第一種方式:
使用js函數eval();
testJson=eval(testJson);是錯誤的轉換方式。
正確的轉換方式需要加(): testJson = eval("(" + testJson + ")");
eval()的速度非常快,但是他可以編譯以及執行任何javaScript程序,所以會存在安全問題。在使用eval()。來源必須是值得信賴的。需要使用更安全的json解析器。在服務器不嚴格的編碼在json或者如果不嚴格驗證的輸入,就有可能提供無效的json或者載有危險的腳本,在eval()中執行腳本,釋放惡意代碼。
js代碼:
function ConvertToJsonForJs() { //var testJson = "{ name: '小強', age: 16 }";(支持) //var testJson = "{ 'name': '小強', 'age': 16 }";(支持) var testJson = '{ "name": "小強", "age": 16 }'; //testJson=eval(testJson);//錯誤的轉換方式 testJson = eval("(" + testJson + ")"); alert(testJson.name); }
第二種方式使用jquery.parseJSON()方法對json的格式要求比較高,必須符合json格式
jquery.parseJSON()
js代碼:
function ConvertToJsonForJq() { var testJson = '{ "name": "小強", "age": 16 }'; //不知道 //'{ name: "小強", age: 16 }' (name 沒有使用雙引號包裹) //"{ 'name': "小強", 'age': 16 }"(name使用單引號) testJson = $.parseJSON(testJson); alert(testJson.name); }