I am trying to access a variable where USER_ID
is dynamic:
jsonParsed.users.[USER_ID].userID;
The USER_ID
will be a large number based on a discord users ID. The user.id is correctly matched up to the id in the json file.
function scrumJoin(user) {
let USER_ID = user.id; //Example: user.id = 147477029364979999
let content = fs.readFileSync('scrumUsers.json');
let jsonParsed = JSON.parse(content);
console.log('JSON parsed user ID: n' + jsonParsed.users.[USER_ID].userID); //point of failure
}
JSON file:
{
"users": [
{
"1111111111111111": [{
"userID": 1111111111111111,
"phase": 1
}]
},
{
"147477029364979999": [{
"userID": 147477029364979999,
"phase": 1
}]
}
]
}
I want USER_ID
to dynamically change based on who is accessing the file. I know this is probably a really simple solution, but I am struggling to figure out how to word it in google and I’m pretty sure GPT is incorrect.
Chat GPT is telling me to format it like this:
jsonParsed.users[USER_ID].userID
but I’m pretty sure that specifies the location of the section I am trying to access in the array, not the name of the section itself.
3
Answers
Changed the formatting of my json file to no longer include unnecessary arrays:
Was able to retrieve the correct data based on a dynamic
USER_ID
with the following code:Well in your case the user data is an array:
So to grab the first entry:
This weird single array stuff often happens in XML to JSON conversions. Not sure where your data is coming from but could be worthwhile addressing that if desired.
You’re making it more complicated than necessary due to your data structure. However, here’s how to do it.
For the data structure:
In order to extract a user with given user id you’d have to do:
I’ve written the above for clarity. The code is as simple as possible so that it is as understandable as possible. You can write it in more modern functional style:
That’s more compact but there’s also a lot more to unpack. However it means exactly the same thing as the code above, find the object in the array that has the USER_ID as the key.
Better data structure.
A better data structure is to simply use an object instead of an array:
With this the code simply becomes:
That’s it, no loops, no filter or find. Just access it directly.
You can even improve it further by removing the array that wraps the user object:
With this data structure your code is simply: