2014-12-31 16 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; });