JSON.parse()與eval()

來源:互聯網
上載者:User

標籤:

一、前言

   和 XML 一樣,JSON 也是基於純文字的資料格式。由於 JSON 天生是為 JavaScript 準備的,因此,JSON 的資料格式非常簡單,您可以用 JSON 傳輸一個簡單的 String,Number,Boolean,也可以傳輸一個數組,或者一個複雜的 Object 對象。

二、包含json對象的字串

基本格式:var jsonData=‘{"data1":"Hello,","data2":"world!"}‘;

三、json的解析方法

 

(1)使用JSON.parse()

<script>
 var str = ‘{"name":"party","age":"23"}‘;
 var ob=JSON.parse(str);
 alert(ob.name);
 alert(ob.age);

 var str = ‘["name","age"]‘;
 var ob=JSON.parse(str);
 alert(ob[0]);
 alert(ob[1]);
</script>

(2)使用eval()

 var str = ‘{"name":"party","age":"23"}‘;
 var ob=eval("("+str+")");

 alert(ob.name);
 alert(ob.age);

 

注意:JSON.parse()可以解析json格式的資料,並且會對要解析的字串進行格式檢查,如果格式不正確則不進行解析,而eval()可以解析任何字串,特別是執行第三方的JSON資料(其中可能包含惡意代碼),使用eval是很危險的,而且容易發生記憶體泄露,所以在代碼中儘可能使用JSON.parse()方法解析字串。

JSON.parse()與eval()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.