I'd like to know how to read the last child that doesn't have the "children" key in it.
Here is my json :
{
"children": [
{
"data" : {
"title" : "Legume",
"attr" : { id: 001 }
},
"children" : [
{
"data" : {
"title" : "Legume frais",
"attr" : { id: 007 }
},
"children" : [
"data" : {
"title" : "Cumcumber",
"attr" : { id: 666 }
},
"data" : {
"title" : "Tomato",
"attr" : { id: 777 }
}
]
}
]
},
{
"data" : {
"title" : "Fruit",
"attr" : { id: 002 }
},
"children" : [
{
"data" : {
"title" : "fruit rouge",
"attr" : { id: 333 }
},
}
]
},
{
"data" : {
"title" : "Viande",
"attr" : { id: 003 }
},
"children" : [
{
....
}
]
},
]}
Here, I'd like to retrieve this part:
"data" : {
"title" : "Cumcumber",
"attr" : { id: 666 }
},
I know how to retrieve this part from a defined depth level. But in my full json, the depth level can be different for each wanted element. How can I be sure to grab the last child that don't have a "children" key ?
You can use list-comprehension to create a sub-list from your original json, and than get the last element of that new sub-list. Something like the following should work:
data = { "records" : [{ "empid": 1, "fname": "X" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] }
foo = [d for d in data['records'] if not 'lname' in d]
foo[len(foo)-1]
>> {'empid': 1, 'fname': 'X'}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.