轉換json和字串的一些方法

來源:互聯網
上載者:User

標籤:lang   utf-8   微軟   tty   png   key   其他   doc   java   

將字串轉換成json對象的方法: var str = ‘{"name1":"value1","name2":"value2"}‘;(json的轉換格式必須是單引號套雙引號) 1.JSON.parse(str); 2.eval("("+str+")"); 3.var json = (new Function("return"+str)()); 將json轉換成字串: 1.JSON.stringgify(json);   相容問題JSON.parse()轉化字串成json對象在 IE7及以下瀏覽器不支援(其他兩種沒問題)可以引進下面的js檔案解決這個問題。https://github.com/douglascrockford/JSON-js
  強制轉換:
 1 <!DOCTYPE html> 2 <htmllang="en"> 3 <head> 4 <metacharset="UTF-8"/> 5 <title>Document</title> 6 </head> 7 <body> 8 </body> 9 <scripttype="text/javascript">10 // 不符合json轉換格式的字串11 var string ="{‘age‘:28,‘sex‘:‘boy‘}";12 // 用json的強制轉換方法來轉換這個字串(new Function("return"+str)());13 var json =(newFunction("return"+string))();14 console.log(json.sex);15 var li = document.createElement("li");16 li.innerText="name:"+json.sex +",age:"+ json.age;17 document.body.appendChild(li);18 </script>19 </html>
View Code

 

效果:  轉換json資料的方法:json就是對象(object),對象就是json;
 1 <!DOCTYPE html> 2 <htmllang="en"> 3 <head> 4 <metacharset="UTF-8"/> 5 <title>轉換json資料</title> 6 </head> 7 <body> 8 </body> 9 <scripttype="text/javascript"src="jquery-3.1.1.min.js"></script>10 <scripttype="text/javascript">11 // 也是利用強制轉換12 data ="{root:[{name:‘1‘,value:‘0‘},{name:‘11‘,value:‘110‘},{name:‘1123‘,value:‘廣東‘},{name:‘1124‘,value:‘附件‘}]}";13 console.log(data);14 var json =(newFunction("return"+data))();15 console.log(json.root);16 $.each(json.root,function(i,v){17 console.log(v);18 var h = v;19 for(key in h){20 console.log(h[key]);21 var $span = $("<span></span><br/>");22 $span.text(h[key]);23 $("body").append($span);24 }25 });26 </script>27 </html>
View Code

 

效果:  



 

轉換json和字串的一些方法

聯繫我們

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