Home > database >  How to get the value of the last key named x in JSON Python
How to get the value of the last key named x in JSON Python

Time:01-26

so I have a JSON file with this inside

{
"vocabulary": [
{
    "id": "1",
    "words": ["hi", "hey"],
    "response": "Hello."
},
{
    "id": "2",
    "words": ["bye", "cya"],
    "response": "Goodbye."
}
]}

And I am wondering how to get the number "2", that would be the value of the last key named "id", however, I had found no solutions till now, can anybody help me? Thanks.

(remember, it's in python)

CodePudding user response:

You could convert your JSON data into a dictionary:

import json

data = '''{
    "vocabulary": [
        {
            "id": "1",
            "words": ["hi", "hey"],
            "response": "Hello."
        },
        {
            "id": "2",
            "words": ["bye", "cya"],
            "response": "Goodbye."
        }
    ]
}'''

data = json.loads(data)

Then, you could access the data you need using slicing:

print(data['vocabulary'][-1]["id"])
>> 2

where vocabulary is the key you want to access, and since you want to get the last element, you can slice it with -1 and only get the id.

CodePudding user response:

You can simply:

import json

with open('my.json') as f:
    data = json.load(f)

# print the 'id' of the last element from the list at the 'vocabulary' key
print(data['vocabulary'][-1]['id'])

CodePudding user response:

test_json = {
    "vocabulary": [
        {
            "id": "1",
            "words": ["hi", "hey"],
            "response": "Hello."
        },
        {
            "id": "2",
            "words": ["bye", "cya"],
            "response": "Goodbye."
        }
    ]}


specific_value = test_json["vocabulary"][-1]["id"]
print(specific_value)
  •  Tags:  
  • Related