简体   繁体   English

使用JSON数据填充Javascript数组

[英]Populate Javascript Array with JSON Data

I am attempting to load a large set of JSON files into an array to be referenced later but Node keeps stating they're undefined. 我试图将一大组JSON文件加载到数组中以供以后引用,但是Node一直在声明它们未定义。 I have code along the lines of: 我的代码大致如下:

var myarray = [];

(...)

var loading_num = 001; // will be incremented in a loop to load data
myarray[loading_num] = fs.readFileSync("data/" + loading_num);

(...)

var reference_num = "001"; // the number being used to pull the appropriate record

(...)

console.log(myarray[reference_num].name); // just testing to attempt to decipher why it doesn't work, I'll actually be using the data obviously

Each JSON file does have a value named name and I have not implemented logic to load all of them yet as I am still just trying to get one to work. 每个JSON文件确实有一个名为name的值,并且我还没有实现加载所有逻辑的逻辑,因为我仍在尝试使其工作。

Am I misunderstading something about Javascript arrays or objects? 我是否对Javascript数组或对象有误解? What am I doing wrong? 我究竟做错了什么? There's a lot of files and they can vary in number so I have to load them in some similar fashion. 文件很多,它们的数量可以变化,因此我必须以类似的方式加载它们。

您应该解析文件内容,以便将原始数据转换为JavaScript对象。

myarray[001] = JSON.parse(fs.readFileSync("data/001"));

First of all. 首先。 fs.readFileSync reads arbitrary files. fs.readFileSync读取任意文件。 If you know your file is JSON and you want to convert it to js you need to parse it using JSON.parse . 如果您知道文件是JSON,并且想要将其转换为js,则需要使用JSON.parse进行解析。

Then 001 is 1 if you want it to be a string wrap it with quotes '001' 如果您希望将其设为字符串,则将其用引号'001'包装,则0011

Array indices starts from 0. 数组索引从0开始。

var myarray = [];
myarray.push(JSON.parse(fs.readFileSync("data/001")));
console.log(myarray[0].name);

Or 要么

var myarray = {}; // use object
myarray['001'] = JSON.parse(fs.readFileSync("data/001"));
var reference_num = "001";
console.log(myarray[reference_num].name);

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

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