我有这个文件“File.txt”,格式为大array[ ]
,在 .txt 文件中放置的该数组的每个索引中,都有一个我稍后要使用的 json 。我需要读取文件,保存每个 json 并使用 javascript 将其推送到 数组 中。每{ content }
, { content 2}
代表一个 json 。
文件.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
}
});
});
});
关于javascript - 如何在 JavaScript 中将 .txt 文件中的数据保存到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45859889/