JSON.stringify =非法访问
我有一个在Javascript中的对象的数组。 我想将这个数组保存到一个.json
文件中。
在将对象添加到文件之前,我将console.log
对象。
// Client Object {id: "1", color: "#00FF00"} Object {id: "2", color: "#FF7645"} Object {id: "3", color: "#FF8845"}
然后我把jsonArray发布到我的nodejs服务器上,像这样:
// Client $.post('/savejson', 'json=' + JSON.stringify(jsonArray)) // This works
抓住这个post,并像这样保存在nodejs中的文件:
app.router.post('/savejson', function(data) { url = '/jsonfiles/something.json' // Nodejs Server fs.writeFile(url, data.body.json, function(error) { if(error) { console.log(error) return } console.log('Saved file: ' + url) })
现在我有一个数组与像这样的对象的JSON文件:
something.json
[ {"id":"1","color":"#00FF00"}, {"id":"2","color":"#FF7645"}, {"id":"3","color":"#FF8845"} ]
我读这样的文件:
// Nodejs Server jsonfile = fs.readFileSync(url, 'UTF-8') // Output jsonfile: [{"id":"1","color":"#00FF00"},{"id":"2","color":"#FF7645"},{"id":"3","#FF8845"}]
parsing它
// Nodejs Server jsonArray = JSON.parse(jsonfile) // Output jsonArray: [{id: '1',color: '#00FF00'},{ id: '2',color: '#FF7645'},{ id: '3',color: '#FF8845'}]
并发回给客户
// Nodejs Server window.newjson(jsonArray)
在我的客户端,
// Client window.newjson = function(jsonArray) { // Here foreach loop } // Output jsonArray: undefined[3] 0: color: "#00FF00" id: "1" __proto__: 1: color: "#FF7645" id: "2" __proto__: 2: color: "#FF8845" id: "3" __proto__: length: 3 __proto__: undefined[0]
并为每个对象我console.log
对象。
产量
// Client {id: "1", color: "#00FF00"} {id: "2", color: "#FF7645"} {id: "3", color: "#FF8845"}
注意到对象字是不同的。
现在我想再次像这样保存同一个文件:
// Client $.post('/savejson', 'json=' + JSON.stringify(jsonArray)) // Not working anymore...
当我在客户端使用JSON.stringify(jsonArray)
时,出现错误: Uncaught illegal access
我也尝试在客户端使用JSON.parse(jsonArray)
,但是这个给我的错误Uncaught SyntaxError: Unexpected token o
当我login第二篇文章之前的jsonArray:
// 1 console.log(jsonArray) // Result Array[3] 0: color: "#00FF00" id: "1" __proto__: 1: color: "#FF7645" id: "2" __proto__: 2: color: "#FF8845" id: "3" __proto__: length: 3 __proto__: Array[0] // 2 console.log(jsonArray.toString()) // Result [object Object],[object Object],[object Object] // 3 JSON.stringify(jsonArray) // Result Uncaught illegal access // 4 JSON.parse(jsonArray) // Result Uncaught SyntaxError: Unexpected token o
我错了什么? 为什么我错过了Object
词?
你必须在发回给客户端之前将jsonArray
string化。
意想不到的标记问题可能是因为您正在对JavaScript对象调用JSON.parse,如下所述: d3.js json未捕获的语法错误意外标记o 。 然后对于客户端的JSON.stringify(jsonArray),你会得到错误“未捕获的非法访问”,通过检查jsonArray是否为null来debugging(因为null仍然是一个对象):
if(variable==null){ // Do stuff console.log etc }
(虽然这是非常罕见的一个问题.strigify应该打印出null)如果这个失败,你的variables也可能是未声明的。 我认为问题可能是@Anthony Grist最初所说的