简体   繁体   中英

JSON_EXTRACT_PATH_TEXT equivalent in python?

SQL has a very useful function called JSON_EXTRACT_PATH_TEXT, which allows to extract data from a json file just by providing the full json path.

What is the easiest way to achieve the same result in python?

I am particularly interested in pandas solutions: json_normalize and read_json do a good job when the json is not too complex, but they become very difficult to use when the json has multiple nested structures.

I'm not familiar with anything that does this out of the box, but it is fairly simple to do. try something like this:

from functools import reduce


class JsonPath:
    @classmethod
    def get(cls, data, path):
        return reduce(cls._get_item, path, data)

    @classmethod
    def _get_item(cls, current_data, current_path):
        return current_data.__getitem__(current_path)

now lets assume your parsed json (use the json built-in) look like this

d = {"a": {"b": [1, 2]}}

and your datapath is an iterable of keys/indices looking like this:

data_path = ["a", "b", 1]

you can then do:

JsonPath.get(d, data_path)

and it will return 2

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