解析"...没有方法'replace''时的JSON错误; [英] JSON Error when parsing "... has no method 'replace'"

查看:122
本文介绍了解析"...没有方法'replace''时的JSON错误;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我以承认自己是一个完整的程序设计和javascript noob开头,这是我麻烦的根源.

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.

我正在尝试从我用json.stringify保存到的文本文件中填充大量自定义对象.当我抓取文件内容和json.parse(them)时,出现以下错误:

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'

导致此错误的代码是:

fs.readFile('/savedcustomobjectarray', function (err, data) {
  var customobjectarray = json.parse(data);
});

我猜我将要解决所有这些错误.我看到有些人提到了此类的序列化器,但是我想再次检查这是否是我需要的(也许会在这种情况下获得一些使用方法的指导).不过,似乎stringify的输出还不错,所以我不确定为什么JSON不能再将笨拙的笨拙重新组合在一起.任何帮助将不胜感激.

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.

text.replace行位于/vendor/commonjs-utils/lib/json-ext.js中,而不是我的代码中.我以为这是JSON的一部分.也许我错了?有没有其他方法可以通过JSON解析我的对象数组?

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?

推荐答案

fs.readFile带有2或3个参数,当仅传递文件名和回调时,您的回调函数将获得以下两个参数(err, data)其中data是原始的缓冲区.

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) where data is a raw buffer.

所以正确的方法是:

fs.readFile('/savedcustomobjectarray', function (err, data) {
  var customobjectarray = JSON.parse(data.toString('utf8'));
});

data.toString将编码作为第一个参数.

data.toString takes the encoding as the first argument.

Alternitavley,您可以将编码指定为fs.readFile的第二个参数,并将其传递给回调函数一个字符串:

Alternitavley you could specify the encoding as the second argument to the fs.readFile and have it pass a string to the callback:

fs.readFile('/savedcustomobjectarray', 'utf8', function (err, data) {
  var customobjectarray = JSON.parse(data);
});

Node API docs 是您最好的朋友!

Node API docs is your best friend!

这篇关于解析"...没有方法'replace''时的JSON错误;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆