【问题标题】:Javascript get value from JSON file [closed]Javascript从JSON文件中获取价值[关闭]
【发布时间】:2014-12-31 18:21:33
【问题描述】:

我有以下 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>

我的问题是这样的,有没有一种方法可以直接编辑值而无需循环,可能类似于编辑 itemid[number] = "customValue" 之类的数组

【问题讨论】:

  • Updating a JSON object using Javascript 的可能重复项[如果 data.txt 的内容使用 JSON 表示法保存到 Javascript 对象]
  • 不完全清楚你的目标是什么
  • 这不是重复的,那个链接在 JSON 中有一个变量,我没有。我使用数组文字作为参数
  • 这是 JSONP,不是 JSON。

标签: javascript jquery html arrays json


【解决方案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
}

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

由于它在您的计算机上,您可以使用 JavaScript 保存它。修改 json 变量后,您可以:

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

【讨论】:

  • 我明白,但我试图将数据保存在 data.txt 文件中,而不是 HTML 文件中。
  • data.txt 在哪里?在你的电脑?在服务器上?
  • 是的,一切都在一个文件夹中。
  • @LawrenceLelo 看看我的更新。
  • 当数据在data.txt中时,为什么会有一个var str包含所有数据
【解决方案2】:

您可以使用数组索引直接跳到特定项目。

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);
}

【讨论】:

  • 我认为这正是我想要的。我已经有一个正在使用的名为 myFunction 的函数。我将如何在不同的函数名称中使用您的代码?有可能吗?
  • @LawrenceLelo 您可以将“myFunction”重命名为您想要的任何其他名称。
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    相关资源
    最近更新 更多