解析“...没有方法“替换”时出现 JSON 错误
让我在序言中承认我是一个完全的编程和 JavaScript 菜鸟,而这一事实是我的麻烦的根源。
我正在尝试从使用 json.stringify 保存的文本文件中填充大量自定义对象。当我获取文件内容和 json.parse(它们) 时,出现以下错误:
var backSlashRemoved = text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'
^
TypeError: Object (contents of file) has no method 'replace'
导致此错误的代码是:
fs.readFile('/savedcustomobjectarray', function (err, data) {
var customobjectarray = json.parse(data);
});
我猜我搞错了。我看到有些人提到了此类事情的序列化器,但我想仔细检查这是否是我所需要的(并且也许获得一些关于如何在这种情况下使用它们的指导)。不过,stringify 输出似乎很好,所以我不确定为什么 JSON 不能将 humpty dumpty 重新组合在一起。任何帮助将不胜感激。
编辑: text.replace 行位于 /vendor/commonjs-utils/lib/json-ext.js 中,而不是我的代码中。我以为这是 JSON 的一部分。也许我错了?有没有不同的方法通过 JSON 解析我的对象数组?
Let me preface this with the admission that I am a complete programming and javascript noob and that fact is the source of my trouble.
I'm trying to populate a large array of custom objects from a text file that I've saved to with json.stringify. When I grab the file contents and json.parse(them), I get the following error:
var backSlashRemoved = text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'
^
TypeError: Object (contents of file) has no method 'replace'
The code that causes this error is:
fs.readFile('/savedcustomobjectarray', function (err, data) {
var customobjectarray = json.parse(data);
});
I'm guessing I'm going about this all wrong. I saw some people mention serializers for this sort of thing, but I wanted to double check if that's what I needed (and maybe get some direction in how to use them in this context). It seems like the stringify output is fine, though, so I'm not sure why JSON can't just put humpty dumpty back together again. Any help would be greatly appreciated.
EDIT:
The text.replace line is in /vendor/commonjs-utils/lib/json-ext.js, not my code. I assumed this was part of JSON. Perhaps I am wrong? Is there a different way to parse my object array through JSON?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
fs.readFile
需要 2 或 3 个参数,当仅传递文件名和回调时,您的回调函数将获取以下两个参数(err, data)
其中data
是一个原始的缓冲区。因此,正确的方法是:
data.toString
将编码作为第一个参数。或者,您可以将编码指定为
fs.readFile
的第二个参数,并让它将字符串传递给回调:Node API docs 是您最好的朋友!
fs.readFile
takes 2 or 3 arguments, when passing only the filename and a callback, then your callback function will get the following two arguments(err, data)
wheredata
is a raw buffer.So the right way to do it would be:
data.toString
takes the encoding as the first argument.Alternitavley you could specify the encoding as the second argument to the
fs.readFile
and have it pass a string to the callback:Node API docs is your best friend!