我在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
抓住帖子并将文件保存在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文件,其中包含以下对象:
[
{"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"}]
解析它
// 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
当我在第二篇文章之前记录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
字?
答案 0 :(得分:2)
在将jsonArray
发送回客户端之前,您必须对其进行字符串化。
答案 1 :(得分:0)
意外的令牌问题可能是因为您在JavaScript对象上调用JSON.parse,如下所述: d3.js json uncaught syntax error unexpected token o。 然后对于客户端的JSON.stringify(jsonArray),您会收到错误“Uncaught illegal access”,如果jsonArray为null,则通过checkking调试(因为null仍然是对象):
if(variable==null){
// Do stuff console.log etc
}
(虽然这很难成为一个问题.strigify应该打印null) 如果失败,您的变量也可以是未声明的。我认为问题可能是@Anthony Grist最初所说的