Search code examples
pythonjsonmultiple-arguments

Python function to read JSON file and retrieve the correct value


I'm reading a JSON file to retrieve some values with my extract_json function and calling it by time_minutes_coords = extract_json("boxes", "time_minutes", "coord") which gives me the right path to my coord value.

  def extract_json(one,two,three):
    with open('document.json') as data_file:
        data = json.load(data_file)
        return data[one][two][three]

But it just works for 3 arguments. What if I would like to use this function for any number of arguments passed? I would like to have something like:

  def extract_json(*args): 
    with open('document.json') as data_file: 
        data = json.load(data_file) 
        return data[args] 

but all the args are displayed in this way:

(args1, args2, args3, args4)

and data(args1, args2, args3, args4) returns nothing. How can I have something like:

data[args1][args2][args3][args4]

for moving to the correct value in the json file?


Solution

  • You can solve it with JSONPath via the jsonpath-rw module. Working sample:

    from jsonpath_rw import parse
    
    obj = {
        "glossary": {
            "title": "example glossary",
            "GlossDiv": {
                "title": "S",
                "GlossList": {
                    "GlossEntry": {
                        "ID": "SGML",
                        "SortAs": "SGML",
                        "GlossTerm": "Standard Generalized Markup Language",
                        "Acronym": "SGML",
                        "Abbrev": "ISO 8879:1986",
                        "GlossDef": {
                            "para": "A meta-markup language, used to create markup languages such as DocBook.",
                            "GlossSeeAlso": ["GML", "XML"]
                        },
                        "GlossSee": "markup"
                    }
                }
            }
        }
    }
    
    keys = ["glossary", "GlossDiv", "GlossList", "GlossEntry", "GlossDef", "para"]
    jsonpath_expr = parse(".".join(keys))
    print(jsonpath_expr.find(obj)[0].value)
    

    Prints:

    A meta-markup language, used to create markup languages such as DocBook.
    

    Here the keys are coming in a form of a list (in your case it is args). Then, the keys are joined with a dot to construct a path to the desired node.