JSON轉string、JSON轉Object

來源:互聯網
上載者:User

標籤:

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);        }

 

 



JSON轉string、JSON轉Object

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.