[Python] python json parser with filename and line numbers?

Discussão em 'Python' iniciado por Stack, Junho 15, 2025.

  1. Stack

    Stack Membro Participativo

    Pythons: "json.loads()" is great - but it is missing an important thing. For each thing found I need to have the LINE NUMBER in the file where it was found.

    The goal is this:

    I have a JSON configuration file that I am reading. There are times when the configuration is 'json-syntactically-correct' - but is wrong for the purposes of configuration.

    Consider, this trivial example representing somebodies name.

    {
    "correct" : {
    "first" : "Fred",
    "last" : "Flintstone"
    },
    "error" : {
    "first" : 1234.6789,
    "last" : "Flintstone"
    }
    }


    In the above both are "syntactically correct" as far as "json.loads" But - the tool using the information wants the "first" field to be a string. Thus it needs to print an error in some reasonable "parser like way"

    I do not want to print an error message like this: FILENAME: invalid "wrong.first" must be a string, not a number

    I want to do this instead: FILENAME:LINENUMBER: "wrong.first" must be a string, not a number

    This example is trivial (a few entries) but the actual use case has hundreds of things and being able to state the filename:linenumber is very helpful

    There seems to be no way to do this with JSON, or YAML, or TOML I really do not want to write my own parser for these.

    In effect, for each "string" In the parsed json, I would like to somehow get the line number of the text.

    Continue reading...

Compartilhe esta Página