在JavaScript中使用JSON文件 [英] Using a JSON file in JavaScript

查看:164
本文介绍了在JavaScript中使用JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在Node.js项目中使用JSON文件的方法,但是它似乎不起作用-

I'm looking to use a JSON file in a Node.js project, but it doesn't seem to be working-

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

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

关于我在做什么错的任何建议吗?运行此命令将产生此错误:

Any suggestions as to what I'm doing wrong? Running this yields this error:

    "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对象.

Where test1 is the first JSON object in my file.

这是我的JSON文件-

This is my JSON file-

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

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

Even before the JSON parsing, how do I read from a file that I will store locally on the server-side? I feel like I'm overcomplicating this.

推荐答案

JSON对象必须包含在{}[]的顶层,因此您不能这样做

A JSON object has to be included in {} or [] at top level, so you cant do

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

使用

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

相反.

这篇关于在JavaScript中使用JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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