Javascript从JSON文件中获取值

时间:2014-12-31 18:21:34

标签: javascript jquery html arrays json

我有以下2个文件,一个HTML文件和一个名为data.txt

的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>
&#13;
&#13;
&#13;

我的问题是,有没有办法直接编辑没有循环的值,可能类似于编辑数组,如itemid [number] =&#34; customValue&#34;

3 个答案:

答案 0 :(得分:2)

我发现很难理解你的要求。您在解析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
}

更新:要将JSON保存到您的服务器上的文件,您需要拥有服务器端脚本。您可能希望使用JSON字符串向脚本发送AJAX HTTP POST请求,然后脚本将更新您的文件。

由于它位于您的计算机上,您可以使用JavaScript保存它。修改json变量后,您可以执行以下操作:

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

答案 1 :(得分: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);
}

答案 2 :(得分:0)

如果你正在使用jQuery,你可以这样做:

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