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] ;
}
JavaScript只能讀取本地文件。我猜你的文本文件在服務器上? – hallleron
@hallleron它是本地的。 –
然後編輯你的文件,用'var data ='作爲它的內容前綴,然後通過'
做這樣的
來源
2017-08-24 11:37:13
我把你的答案在標籤,它應該工作,但它給了我這個錯誤:Uncaught ReferenceError:$未定義; –
這意味着你需要加載jquery。 –
你需要添加jQuery腳本 –