JSON(1):如何将符合json语法的字符串转换为一个JS对象

来源:互联网 发布:咕咚运动软件最新 编辑:程序博客网 时间:2024/06/17 06:55

假设服务器已经向浏览器返回了一个符合json语法的字符串,那我们如何将这个特殊的字符串转换为一个JS对象呢?

我们可以利用prototype库中的一个函数evalJSON( )来将符合json语法的字符串转换为一个JS对象。

<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"><script src="prototype1.6.js"></script></head><body><script>function test(){var str='{"name":"tom","age":20}';//alert(typeof str);var person=str.evalJSON();alert(person.name+" "+person.age);}function test2(){var str='[{"name":"tom","age":20},{"name":"green","age":30}]';var persons=str.evalJSON();alert(persons[1].name+" "+persons[1].age);}</script><a href="javascript:test()">test</a><br><a href="javascript:test2()">test2</a></body></html>