Get last item in JSON array with Python

In a JSON entry that looks like this

{
"numbers":["1", "2", "3"]
}

I’m trying to pull 3 from numbers. How do I do this? Right now I have:

lastEntry = json.loads(page.decode())['numbers', -1]

which throws:

KeyError: ('numbers', -1)

>Solution :

A simple way of working with JSON in python is converting the JSON object to a dictionary and working from there.

If the JSON is a string:

f='{"numbers":["1", "2", "3"]}'
d=json.loads(f)
d['numbers'][-1]

If the JSON is in a file:

with open("test.json") as f:
    d = json.load(f)
d['numbers'][-1]

Leave a Reply