I'm trying to get my JSON file content into a JS variable, so I can start using what was in the JSON file. I'm having trouble figuring out how to parse each category and assigning them to a variable in JS.
So on the JS side, I would like for it to be somthing like this:
var 1 = jeff
var 2 = Internal
and so on...
Use JSON.parse()
. I'm assuming the JSON
is in a file. Also assuming var 1 = ...
means first 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.