Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading