0

So I am doing a project right now requiring the storage of user preferences with JSON. I have searched for a decent amount of time now but can find no solution.For example sake There are three variables user, permissions, serverid . I figured this would work.

tempObject = {
    user: []
};

tempObject.user.push({perm:permissions, server:serverid});

Then i would stringify and turn into a JSON. However the output came out like this:

{user[{perm:4, server:883}]}

This was my desperate attempt at grouping the perm and server variables under the indivisuals UserID so further down in the code i can fetch the permissions of each userID. But as you can see it didnt print the user variable, just changed it to an array and took user as a litteral string.

tl;dr In short i need help being able to have a JSON file be written to where it stores the perm and serverID under the UserID.

2 Answers 2

2

Make user an object. Change this:

user: []

for this:

user: {}

and then set the keys like this:

user.perm = 4;
user.server = 883;
Sign up to request clarification or add additional context in comments.

Comments

0

For security reasons, client-side JavaScript is not permitted to write to the disk. This sounds like you need a database.

You could leverage localStorage, or perhaps a cookie as an alternate to a database.

I think you should change the users array to an object; that way could key by userID.

for example:

var data = {
  users: {}
};

const userID = 1234; // or could be a string like 'john_doe'
const userPermissions = { perm: 4, server: 883 };

// set the user's permissions
data.users[userID] = userPermissions;

// fetching user's permissions
const userData = data.users[userID];
console.log('User ' + userID +' has perm = ' + userData.perm + ' and server = ' + userData.server);

Now saving and loading of this data using local storage is easy:

function saveData() {
  localStorage.setItem('UserData', JSON.stringify(data));
}

function loadData() {
  data = JSON.parse(localStorage.getItem('UserData'));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.