繁体   English   中英

如何将数据从.txt文件保存到JavaScript中的数组?

[英]How can i save data from a .txt file to an array in JavaScript?

我有一个格式为big array[ ]文件“ File.txt”,在.txt文件中放置的该数组的每个索引中,都有一个我想稍后使用的json 我需要读取文件,保存每个json并使用javascript将其推送到数组中。 每个{ content }{ content 2}代表一个json

File.txt

[
 {
  "nodes": [
    {"id": "Source","label":"name","group": 0},
    {"id": "Parent_1","label":"name","group": 1},
    {"id": "Parent_2","label":"name","group": 1},
    {"id": "Parent_3","label":"name","group": 1},
    {"id": "Child_1","label":"name","group": 2},
    {"id": "Child_2","label":"name","group": 2},
    {"id": "Child_3","label":"name","group": 2},
    {"id": "Child_4","label":"name", "group": 3}
  ],
  "links": [
    { "source": "Source","target": "Parent_1"},
    { "source": "Source","target": "Parent_2"},
    { "source": "Source","target": "Parent_3"},
    { "source": "Source","target": "Child_1"},
    { "source": "Source","target": "Child_2"},
    { "source": "Source","target": "Child_3"},
    { "source": "Child_2","target": "Child_4"}
  ]
} ,
{
  "nodes": [
    {"id": "Source","label":"name","group": 0},
    {"id": "Parent_1","label":"name","group": 1},
    {"id": "Parent_2","label":"name","group": 1},
    {"id": "Parent_3","label":"name","group": 1},
    {"id": "Child_1","label":"name","group": 2},
    {"id": "Child_2","label":"name","group": 2},
    {"id": "Child_3","label":"name","group": 2},
    {"id": "Child_4","label":"name", "group": 3}
  ],
  "links": [
    { "source": "Source","target": "Parent_1"},
    { "source": "Source","target": "Parent_2"},
    { "source": "Source","target": "Parent_3"},
    { "source": "Source","target": "Child_1"},
    { "source": "Source","target": "Child_2"},
    { "source": "Source","target": "Child_3"},
    { "source": "Child_2","target": "Child_4"}
  ]
} 
]

我想到了这样的事情:

//The array i want to save all the data in
NewArray=[];

//Get the file name
 var File = document.getElementById('File.txt');

//Make a loop so i can read each index of the file and save the content in the new array
for (i = 0; i < array.length; i++) { 
    NewArray[i] = "File.[i] ;
}

像这样做

$(document).ready(function() {
    $("#lesen").click(function() {
        $.ajax({
            url : "helloworld.txt", //get the file from local/server 
            dataType: "text",
            success : function (data) {
                var arrData = data; //data are in the form of array with json data
            }
        });
    });
}); 

数据将像这样显示

一种使其工作的方法是编辑文本文件,并在其内容前添加前缀

var data = 

然后通过以下方式加载它:

<script src="file.txt"></script>

一旦有了它,就可以通过data变量访问data

暂无
暂无

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

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