-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

jamesnet214
  • 1,044
  • 13
  • 21
CunningBard
  • 144
  • 11

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,824
  • 17
  • 99
  • 186
Pratap Alok Raj
  • 1,098
  • 10
  • 19
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,488
  • 1
  • 9
  • 18