2017-08-24 88 views
0

我有这个文件,“File.txt”格式化为一个大的array[ ],在这个数组的每个索引放置在.txt文件中有一个json我想以后使用。我需要读取文件,保存每个json并将其推入阵列使用javascript。每个{ content }{ content 2}代表json如何将数据从.txt文件保存到JavaScript中的数组中?

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] ; 
} 
+0

JavaScript只能读取本地文件。我猜你的文本文件在服务器上? – hallleron

+0

@hallleron它是本地的。 –

+1

然后编辑你的文件,用'var data ='作为它的内容前缀,然后通过'

2

做这样的

$(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

+0

我把你的答案在标签,它应该工作,但它给了我这个错误:Uncaught ReferenceError:$未定义; –

+1

这意味着你需要加载jquery。 –

+0

你需要添加jQuery脚本 –

相关问题