2014-12-31 19 views
0

我有以下2個文件,HTML文件,並稱爲JSON文件data.txt中的Javascript得到JSON文件值

在JSON:

myFunction([ 
{ 
"itemid": "0", 
"itemname": "air", 
"currentprice": "5.0" 
}, 
{ 
"itemid": "1", 
"itemname": "stone", 
"currentprice": "5.0" 
}, 
{ 
"itemid": "2", 
"itemname": "grass", 
"currentprice": "5.0" 
}, 
{ 
"itemid": "3", 
"itemname": "dirt", 
"currentprice": "5.0" 
}, 
{ 
"itemid": "4", 
"itemname": "cobblestone", 
"currentprice": "5.0" 
}, 
{ 
"itemid": "5", 
"itemname": "plank", 
"currentprice": "5.0" 
} 
]); 

所以基本上,我唯一的知識從該文件的方式來修改或視圖數據與如下所示的環:

<div id="id01"></div> 
 

 
<script> 
 
function myFunction(arr) { 
 
    var out = ""; 
 
    var i; 
 
    for(i = 0; i<arr.length; i++) { 
 
     out += '<a href="' + arr[i].url + '">' + arr[i].itmid + '</a><br>'; 
 
    } 
 
    document.getElementById("id01").innerHTML = out; 
 
} 
 
</script> 
 

 
<script src="data.js"></script>

我的問題是這樣的,在那裏沒有環直接編輯值的方法,有可能類似於像的itemid [數字]編輯陣列=「customValue」

+0

可能重複://stackoverflow.com/questions/8702474/updating-a-json-object-using-javascript)[如果data.txt的內容保存到使用JSON記法的Javascript對象] – alex

+0

不完全清楚你的目標是什麼 – charlietfl

+1

這不是重複的,該鏈接在JSON中有一個變量,我不這樣做。我使用數組字面量作爲參數 – Dragneel

回答

1

我覺得很難理解你的要求。您在解析JSON文件時遇到問題嗎?如果是的話,做的事:

var str = '{"stuff":[{"itemid": "0","itemname": "air","currentprice": "5.0"},{"itemid": "1","itemname": "stone","currentprice": "5.0"},{"itemid": "2","itemname": "grass","currentprice": "5.0"},{"itemid": "3","itemname": "dirt","currentprice": "5.0"},{"itemid": "4","itemname": "cobblestone","currentprice": "5.0"},{"itemid": "5","itemname": "plank","currentprice": "5.0"}]}'; 
var json = JSON.parse(str); //str is the json 
for (int i = 0; i < json.stuff.length; i++) 
{ 
    //Do whatever with json.stuff[i]. i.e.: 
    document.getElementById("id01").innerHTML += json.stuff[i].itemid; // puts each item's ID 
} 

UPDATE:要將JSON保存到服務器上的一個文件,你需要有一臺服務器片面的腳本。您可能希望使用JSON字符串向您的腳本發送AJAX HTTP POST請求,然後腳本將更新您的文件。

由於它在您的計算機,您可以使用JavaScript保存它。在修改json變量之後,你可以這樣做:

var blob = new Blob([JSON.stringify(json)], {type: "text/plain;charset=utf-8"}); 
saveAs(blob, "thefile.txt"); 
+0

我明白,但我試圖保留data.txt文件中的數據,而不是HTML文件。 – Dragneel

+0

data.txt位於何處?在你的電腦?在服務器上? – Shahar

+0

是的一切都在一個文件夾中。 – Dragneel

0

可以使用數組索引直接跳到特定項目。

function myFunction(arr) { 
    console.log(arr[0].itemid); 
    console.log(arr[0].itemname); 
    console.log(arr[0].currentprice); 

    console.log(arr[1].itemid); 
    console.log(arr[1].itemname); 
    console.log(arr[1].currentprice); 
} 
+0

我認爲這正是我要找的。我已經有一個名爲myFunction的函數正在使用。我將如何在不同的函數名稱中使用您的代碼?可能嗎? – Dragneel

+0

@LawrenceLelo你會將「myFunction」重命名爲任何你想要的。 – alex

0

如果你正在使用jQuery你可以做一些像這樣:的[更新使用Javascript JSON對象(HTTP

$.grep(a, function(e){ return e.itemid == 1; });