0

I've seen this asked a multitude of times, but I think the JSON I'm looking to access is a bit different. I'm looking at a JSON with this format:

{
  "timestamp": 1589135576,
  "level": 20,
  "gender": "Male",
  "status": {},
  "personalstats": {},
  "attacks": {
    "103307874": {
      "code": "cc7bc5ab6fbd54f49a2e879c49e70183",
      "result": "Mugged",
      "chain": 2,
      "modifiers": {
        "fairFight": 3,
        "war": 1,
        }
      },
    "103320473": {
      "code": "3184c1e2c9662fd70a21f03a637cb02e",
      "result": "Mugged",
      "chain": 1,
    "modifiers": {
      "fairFight": 1.07,
      "war": 1,
      }
    },
  }
}

There are 98 more "attack" below the first two here.

Now I thought I could access the first attacks result with this code, but it results in a key error. Anyone understand why?

currentresponse = requests.get("URL")
json_obj = json.loads(currentresponse.text)
lastresult = json_obj["attacks"][0]["result"]

As a "bonus" I can access the result of the attack through the following code.

json_obj["attacks"]["103320473"]["result"]
1
  • 1
    Because attacks is not a list. Commented May 10, 2020 at 19:05

1 Answer 1

1

Yeah, you can't access with json_obj["attacks"][0], because it's not a list, and hence doesn't have indexing like a list. These are nested dicts, so you have to access them by dict rules (access by key)

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

1 Comment

Thanks! As I understand it dicts are inherently unordered, which is somewhat confirmed by the timestamps for the attacks not being in order. Is there any way I can sort and access the attack with the highest "timestamp" (its in the json but I cut it out of OP for readability) directly? I've worked my way around it by storing all attacks in my db and finding the newest one there, but its not very scalable or clean I think

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.