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

时间:2017-08-24 11:00:56

标签: javascript jquery arrays loops

我有这个文件,“File.txt”格式化为一个大array[ ],在.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] ;
}

2 个答案:

答案 0 :(得分:3)

这样做

$(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
            }
        });
    });
}); 

data will be shown like this

答案 1 :(得分:1)

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

var data = 

然后通过以下方式加载:

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

完成后,您可以通过data变量访问数据。