简体   繁体   English

在JSON文件中使用JavaScript变量

[英]Use JavaScript variables in JSON file

I'm trying to reference self-key to in a JSON file in a simple Hello World NodeJS app. 我正在尝试在一个简单的Hello World NodeJS应用程序的JSON文件中引用自密钥。

{
    "person": {
        "first_name": "Aminul",
        "last_name": "Islam"
    },
    "full_name": "{$person.first_name} {$person.last_name}"
}

and the app file. 和应用文件。

const person = require('./app.json');

console.log(person.full_name);

Expecting result: 预期结果:

Aminul Islam

Result: 结果:

{$person.first_name} {$person.last_name}

it won't work in JSON here is a js workaround 这在JSON中不起作用这是一个js解决方法

const data = {
  "person": {
      "first_name": "Aminul",
      "last_name": "Islam"
  }
}

data["full_name"] = `${data.person.first_name} ${data.person.last_name}`
module.exports = data

and import it 并导入

const person = require('./app.js');

console.log(person.full_name);

JSON and Node.js simply don't work like that. JSON和Node.js根本不能那样工作。

To get that effect you'd need to so something along the lines of: 要获得这种效果,您需要遵循以下步骤:

  1. Read the raw JSON data using something like fs.readFile 使用fs.readFile类的fs.readFile读取原始JSON数据
  2. Pass the result through a template engine 通过模板引擎传递结果
  3. Pass the output of the template engine though JSON.parse . 通过JSON.parse传递模板引擎的输出。

This is because JSON does not support the use of {$person.first_name} . 这是因为JSON不支持使用{$person.first_name} It treats it as a string. 它将其视为字符串。 JSON does no processing for you and is simply a method of holding data. JSON不会为您处理数据,而只是保存数据的一种方法。

Your method for reading in the JSON data also appears a little odd. 您读取JSON数据的方法也有些奇怪。 I actually have no idea how that's working for you. 我实际上不知道这对您有什么帮助。 The more robust method is as follows: 更可靠的方法如下:

var fs = require("fs");
var file = fs.readFileSync("./app.json");
var jsonData = JSON.parse(file);
var person = jsonData.person;
console.log(person.first_name + " " + person.last_name);

You already have your data defined no need to expand the contents of your JS file with duplicate data (even if it is in another format). 您已经定义了数据,无需使用重复的数据来扩展JS文件的内容(即使它是另一种格式)。

If you truly need that formatting, generate that data when you create the JSON. 如果您确实需要这种格式,请在创建JSON时生成该数据。 If you already have that information being inserted anyway, it's just one more step to add a variable with that formatting. 如果您已经插入了该信息,那么仅是添加具有该格式的变量的第一步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM