toJSONString的问题
在百度百科上查JSON,上面说json对象可以用toJSONString()函数可以将任何JS对象(当然包括JSON对象)转换成JSON字符串,但我试了以后浏览器总报错,说是没有这个函数。怎么回事?
<script>
var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
] } ;
var newJSONtext = people.toJSONString();
------解决方案--------------------
老版本的浏览器不支持这个方法。我推荐到下面这个页面去下载 json2.js ,在你的页面中引用该 js,然后调用 JSON.stringify() 方法将 JavaScript 对象转化成 JSON 字符串。
https://github.com/douglascrockford/JSON-js
------解决方案--------------------toJSONString()又不是js原生的方法,需要引入相应的库或自己定义后才能用
------解决方案--------------------var newJSONtext = JSON.stringify(people);