0

Basically what I want to do is to read a json file and firstly fetch a guild's ID from it and then search for a user's ID in this guild.

Let's say this is the sample of json file:

{Guilds ID}:
    {Users ID}:
        Value: "Yes"
        Value2: "No"
    {Users ID}:
        Value: "Yes"
        Value2: "No"
{Guilds ID}:
    {Users ID}:
        Value: "Yes"
        Value2: "No"
    {Users ID}:
        Value: "Yes"
        Value2: "No"

I tried using:

Variable[message.guild.id] = {
    User: "User ID"
    }

but this won't really work as I can't get variables only to specific user's ID like this. I probably made it complicated but can someone please help? I also want to save the file. Thanks.

1
  • 3
    Instead of "let's say" it is better to give the actual JSON in the example. Your example is not valid JSON format. Commented Mar 17, 2019 at 20:21

1 Answer 1

1

How about the following:

var data = {
  "guild1": {
    "userId1": {
      "Value": "Yes",
      "Value2": "No"
    },
    "userId2": {
      "Value": "Yes",
      "Value2": "No"
    }
  },
  "guild2": {
    "userId3": {
      "Value": "Yes",
      "Value2": "No"
    }
  }
}

if (data["guild1"].hasOwnProperty("userId2")) {
  console.log("Value for userId2 in guild1: " + data["guild1"]["userId2"].Value);
}

if (!data["guild1"].hasOwnProperty("userId5")) {
  data["guild1"]["userId5"] = {
    "Value": "Yes",
    "Value2": "No"
  }
}
console.log("Added new user userId5 to guild1")

If your JSON data structure consists of nested objects, where guild objects contain user objects, you can check if an user belongs to a guild by using the hasOwnProperty()method as shown in the example above. Note, you shall not use data["guild1"]["userId<x>"] instead as this would add a property "userId<x>": undefined if it does not exist in the given guild! See also jsFiddle.

EDIT: As you also asked how to add an user to a guild I have extended my example. Regarding reading and writing JSON have a look here: reading and writing json file using javascript

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I'll look at it tomorrow and I would try and geet it to work. If something would go wrong I'll ask you if you don't mind.
Okay, sorry for not responding for so long but I was quite busy. Anyways, thanks for your answer it worked! :D Thanks for this again. One note though, I prefer checking if certain property exists just by doing "if (!data["guild1"]["userID"]) {Do something}. I think it's much easier and clearer to see.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.