[英]How can I assign a JavaScript variable by parsing a JSON file?
I have a database server that will be running a script to generate this given file daily: 我有一个数据库服务器,它将运行脚本来每天生成此给定文件:
{"data": [
{"variable":"var1","value": "123"},
{"variable":"var2","value": "456"},
{"variable":"var3","value": "789"}]}
I am trying to parse this file to set three javascript variables for a HTML canvas element. 我正在尝试解析此文件,以为HTML canvas元素设置三个javascript变量。
So far, I'm thinking I'll parse the JSON file 到目前为止,我认为我将解析JSON文件
var JSONfile = './file.json';
var getData = JSON.parse(JSONfile);
Then a for
loop to assign the variables 然后是for
循环来分配变量
for (i = 0; i < getData.length; i++) {
var getData.variable=getData.Value;
}
And I'm hoping to get results of: 我希望得到以下结果:
var var1 = 123;
var var2 = 456;
var var3 = 789;
But var getData.variable=getData.Value;
但是var getData.variable=getData.Value;
breaks. 休息。 What am I missing? 我想念什么?
JSON.parse() expects a JSON string, when you are passing it a file. JSON.parse()在传递文件时需要JSON字符串。
The first thing you need to do is use AJAX to get the contents of the file into a variable. 您需要做的第一件事是使用AJAX将文件内容转换为变量。 Either use a library like jQuery (see http://api.jquery.com/jquery.getjson/ ) or from scratch in JavaScript. 可以使用jQuery之类的库(请参阅http://api.jquery.com/jquery.getjson/ ),也可以使用JavaScript从头开始。 But don't waste your time on the "from scratch" version unless you have to. 但是除非必须,否则不要在“从头开始”版本上浪费时间。
Use jQuery to get the contents of the file into an object, and pass the inner data (an array) to a function called doSomething(): 使用jQuery将文件的内容放入对象中,然后将内部数据(数组)传递给名为doSomething()的函数:
$(function () {
$.getJSON("./file.json", function (data) {
}).success(function (data) {
myArr = data.data;
doSomething(data.data);
});
});
Here, you iterate through the passed array, which contains elements that have a .variable and a .value property. 在这里,您遍历传递的数组,该数组包含具有.variable和.value属性的元素。 This writes both properties of each element to the console, for your viewing pleasure: 这会将每个元素的两个属性都写入控制台,以供您查看:
function doSomething(arr) {
for (i = 0; i < arr.length; i++) {
console.log(arr[i].variable + ': ' + arr[i].value);
}
}
You can also access the properties directly by the index as follows: 您还可以通过索引直接访问属性,如下所示:
alert(jsonFromFile.data[2].variable); // Will alert "var3"
alert(jsonFromFile.data[2].value); // Will alert "789"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.