【问题标题】:"Unexpected token in JSON at position 0"?“位置 0 的 JSON 中的意外标记”?
【发布时间】:2018-03-02 03:11:56
【问题描述】:

我正在编写一个导入 JSON 文件的 node.js 模块:

const distDirPath = "c:/temp/dist/";
const targetPagePath = "c:/temp/index.html";
const cliJsonPath = "C:/CODE/MyApp/.angular-cli.json";
const fs = require('fs');

function deployAot()
{
    var version = JSON.parse(fs.readFileSync(cliJsonPath, 'utf8')).version;
}

// export the module
module.exports = {
    DeployAot: deployAot
};

我在https://jsonlint.com/ 中验证了上面 json 文件的内容,它是有效的 json,但是 deployAot() 中的第一行代码在我执行节点模块时返回以下错误:

"Unexpected token  in JSON at position 0"

这是具体的json:

https://jsonblob.com/cd6753d2-9e51-11e7-aa97-2f95b001b178

知道这里可能存在什么问题吗?

【问题讨论】:

  • 也许给我们看一个 JSON 本身?
  • 字节序标记?
  • 尝试将您的 JSON 简化为 1 个键值对。然后打印fs.readFileSync(cliJsonPath, 'utf8')的结果,看看字符串开头有没有奇怪的字符。
  • @LEQADA 我用 json 的 url 更新了我的原始帖子
  • 我说的是你在解析后缺少project 键

标签: json node.js angular


【解决方案1】:

正如@cartant 在 cmets 中已经提到的问题,很可能您会在文件的开头得到一个特殊字符(字节顺序标记)。

我会尝试替换这个

fs.readFileSync(cliJsonPath, 'utf8')

有了这个

fs.readFileSync(cliJsonPath, 'utf8').substring(1)

去掉字符串中的第一个字符,看看会发生什么。


GitHub问题fs.readFileSync(filename, 'utf8') doesn't strip BOM markers

问题建议:

解决方法:

body = body.replace(/^\uFEFF/, '');

读取一个 UTF8 文件后,您不确定它是否可能有 BOM 标记。

【讨论】:

  • substring(1) 是解决方法!
  • @PatrickRoberts - 在 Visual Studio 中打开文件时,文件以“{”开头。不知道神奇的第一个字符来自哪里。或者如何摆脱它
  • @user8570495 我想如果你用十六进制编辑器打开你的文件,你会看到那个神奇的特殊字符
猜你喜欢
  • 1970-01-01
  • 2020-10-31
  • 2021-10-22
  • 2021-05-21
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多