-2

I'm learning JSON and I couldn't find anything about accessing Json Variables

JSON File:

{
  "Users": [
    {
      "username": "LGLGLG"
    },
    {
      "username": "Number"
    },
    {
      "username": "Polly1"
    }
  ],
  "LGLGLG-U": "LGLGLG",
  "LGLGLG-P": "lol123",
  "LGLGLG-B": 0
}

I'm trying to access the JSON Integer LGLGLG-B

james.lee
  • 856
  • 11
  • 19

2 Answers2

1

Json is analogous to dictionaries in Python. So you can directly access element in Python by saying dic[KEY] to get the value where dic is the dictionary and KEY is the key against which you want to access the value. For your case, you can do something like below:

dic = {
  "Users" : [{
    "username" : "LGLGLG"
  }, {
    "username" : "Number"
  }, {
    "username" : "Polly1"
  }
  ],
  "LGLGLG-U" : "LGLGLG",
  "LGLGLG-P" : "lol123",
  "LGLGLG-B" : 0
}

result = dic["LGLGLG-B"]
print(result)

In your case the dic is dictionary and LGLGLG-B is the key and 0 is the value you are trying to access.

halfer
  • 19,471
  • 17
  • 87
  • 173
Alok Raj
  • 1,000
  • 9
  • 17
1

Python doesn't have JSON variables. It has dictionaries. The JSON in the file is just a string. You need to read lines from the file (which I will not show here), then use the python json library to load it into a dictionary then access it with bracket notation.

import json

your_json = """
{
  "Users" : [{
    "username" : "LGLGLG"
  }, {
    "username" : "Number"
  }, {
    "username" : "Polly1"
  }
  ],
  "LGLGLG-U" : "LGLGLG",
  "LGLGLG-P" : "lol123",
  "LGLGLG-B" : 0
}
"""

data = json.loads(your_json)
print(data["LGLGLG-B"])
Kevin Welch
  • 1,398
  • 1
  • 8
  • 17