[Python] How to parse a JSON from a file and record lines/colums each parsed object had in the...

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    Assuming I parse a JSON file like:

    { "foo": [ "bar", "baz" ] }


    in Python via something like:

    with open("example.json") as f:
    j = json.load(f)


    I'd want a way to get the line number and position of e.g. j["foo"][0] (which is `"bar") in the text file.

    What line number is, is probably obvious (for the example it would be line 2). Position is at least the column where the object starts in the JSON file, but ideally also the last column of it (for the example it would be columns 11-15).

    Ideally all this would somehow work with the standard library json and not add some other 3rd party JSON parser as dependency.

    The motivation for all this is to give the user feedback, where exactly the syntax o some JSON file failed, and with that I don't mean the syntax of JSON itself, but if my JSON is e.g. defined in a way so that j["foo"][0] must be string, but isn't.

    Looked at several other JSON decoders for Python, but as far as I could see, none supported this.

    Continue reading...

Compartilhe esta Página