【发布时间】:2013-04-05 12:18:49
【问题描述】:
我有一个包含 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 文件,其中包含一个包含如下对象的数组:
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"}]
解析
// 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 这个词?
【问题讨论】:
-
如果没有看到代码,我们将无能为力。听起来你打电话给
JSON.stringify()和JSON.parse()是在错误的事情上。 -
我不想看到任何接近它的地方;仅保存到 .json 文件并从中读取的部分。
-
@Bondye 显然这是不可能的,因为他无法将对象从服务器传递到客户端。他必须在某个地方把它串起来。代码sn-p不完整,感觉那里有错误。
-
@Bondye 在服务器端对
jsonArray进行字符串化的代码在哪里? -
@Bondye 你已经写过你读过这样的文件(在服务器端):
jsonfile = fs.readFileSync(url, 'UTF-8')然后你解析它(在服务器端)jsonArray = JSON.parse(jsonfile)然后你把它发回给客户window.newjson(jsonArray)。我在问:你在哪里字符串化jsonArray?换句话说:你是如何发回数据的?附言对不起,出于某种原因,我认为你不是 OP。 ://
标签: javascript json node.js