【问题标题】:Using a JSON file in JavaScript在 JavaScript 中使用 JSON 文件
【发布时间】:2011-04-22 19:11:01
【问题描述】:

我希望在 Node.js 项目中使用 JSON 文件,但它似乎不起作用 -

var JsonPath = '../../folderOfjsonFiles';
var JsonFile = JsonPath + 'test.json';

var parseThis = JSON.parse(JsonFile);
console.dir(parseThis);

关于我做错了什么有什么建议吗?运行这个会产生这个错误:

    "test1": {
        ^
   uncaught: SyntaxError: Unexpected token :
    at Module._compile (module.js:399:25)
    at Object..js (module.js:410:10)
    at Module.load (module.js:336:31)
    at Function._load (module.js:297:12)
    at require (module.js:348:19)

其中 test1 是我文件中的第一个 JSON 对象。

这是我的 JSON 文件-

{
    "test1": {
        "testname": "alpha",
        "password": "password"
    }
}

即使在 JSON 解析之前,我如何从服务器端本地存储的文件中读取数据?我觉得我过于复杂了。

【问题讨论】:

  • 发布您的“JSON”文件。或者至少是前几行。
  • 所以上面的文件抛出了 SyntaxError(jsonlint.com) bc 它的有效 JSON?

标签: javascript json parsing


【解决方案1】:

JSON 对象必须包含在顶层的 {}[] 中,所以你不能这样做

"test1": {...},
"test2": {...}

使用

{
  "test1": {...},
  "test2": {...}
}

改为。

【讨论】:

  • 我相信它的格式已经正确了- { "test1": { "testname": alpha, "password": password } }
【解决方案2】:

我将我的 Express 服务器配置存储在一个文件中并像这样读取它:

var fs = require('fs');
var path = require('path');
var conf = fs.readFileSync(path.join(__dirname, './config.json'), 'utf8');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 2023-03-05
    • 2020-09-23
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    相关资源
    最近更新 更多