简体   繁体   中英

Searching in a complex json information in an tinyDB

I've the following json information in a tinyDB

{
"_default": {
    "1": {
        "status": {
            "timestamp": "2021-03-21T15:12:04.025Z",
            "total_count": 4436
        },
        "data": [
            {
                "id": 1,
                "name": "abc"
            },
            {
                "id": 2,
                "name": "def"
            },
            {
                "id": 1,
                "name": "qwe"
            }
        ]
    }
}

}

I understand how to search in the status section ie

listings = db.table('_default')
E = Query()
print(listings.search(E.status.total_count == 4436))

But how can I search inside the data section with []?

You could load it as a string and parse it by index, since data is a list. So just change [0] with whatever index you are interested in seeing in the data piece

import json

x = """{
   "_default":{
      "1":{
         "status":{
            "timestamp":"2021-03-21T15:12:04.025Z",
            "total_count":4436
         },
         "data":[
            {
               "id":1,
               "name":"abc"
            },
            {
               "id":2,
               "name":"def"
            },
            {
               "id":1,
               "name":"qwe"
            }
         ]
      }
   }
}"""

y = json.loads(x)


print(y["_default"]["1"]["data"][0])

results in:

{'id': 1, 'name': 'abc'}

EDIT: I see you are working with DB tables for this, so you it wouldn't apply exactly but you can get the parsing by index idea at least

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM