[英]How can I parse my JSON file that contains strings, and numbers, and assign each category to a variable in JS?
I'm trying to get my JSON file content into a JS variable, so I can start using what was in the JSON file.我正在尝试将我的 JSON 文件内容放入 JS 变量中,以便我可以开始使用 JSON 文件中的内容。 I'm having trouble figuring out how to parse each category and assigning them to a variable in JS.
我无法弄清楚如何解析每个类别并将它们分配给 JS 中的变量。
So on the JS side, I would like for it to be somthing like this:所以在 JS 方面,我希望它是这样的:
var 1 = jeff
var 2 = Internal
and so on...等等...
Use JSON.parse()
.使用
JSON.parse()
。 I'm assuming the JSON
is in a file.我假设
JSON
在一个文件中。 Also assuming var 1 = ...
means first var one = ...
还假设
var 1 = ...
表示第一个var one = ...
var jsonObject = JSON.parse(file);
var one = jsonObject.invites[someIndex].sender_id; // "jeff"
var two = jsonObject.invites[someIndex].vector; // "Internal"
You can use the following code to create global variables by the same name as json object properties.您可以使用以下代码创建与 json 对象属性同名的全局变量。
data = {
"invite_id": 1,
"sender_id": "jeff",
"sig_id": 25121,
"invite": "The Owner has invited you",
"vector": "Internal",
"invite_time": 1398892261,
"status": 'read'
}
//Iterate the object
for (var property in data) {
if (data.hasOwnProperty(property)) {
window[property] = data[property] //create global variables by property name
}
}
console.log(vector); //outputs 'Internal'
But the correct pattern is to create your variables within a private scope object.但正确的模式是在私有范围对象中创建变量。 You can do it by replacing
window
with your private scope object.您可以通过将
window
替换为您的私有范围对象来实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.