[Python] convert jsonc to json via regex

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

  1. Stack

    Stack Membro Participativo

    Hi I need to preprocess a JSONC (super set of json that supports comments like //this one and /* this one */) to transform it into normal JSON (standard) using python regex only. Started to believe this can't be solved with regex only, but via semantic processing, maybe something like tree-sitter, but asking regex for now.

    As a test example, I have the following: (
    note 1: If you remove everything that's in the comments manually, you get a clear json;
    note 2: The JSON is always pretty print;
    note 3: The problem statement is very clear, and the code below is just an example, meaning that there might be cases not covered in here;
    ).

    //tried this sed -r 's#\s//[^}]*##'
    // also tried this sed -r 's#\s//[^}]*##'
    [
    {
    "test1" : "http://test.com",
    "test2" : "http://test.com",//test
    // any thing
    "ok" : 3, //here 2
    "//networkpath1" : true, //whynot
    "//networkpath2" : true
    // ok

    },//eof
    {
    "statement" : "I like test cases"
    }//eof
    ]



    I might allow a couple of conceptions like,
    "forget about python, just give me something that works, similar to the failed sed attempts commented out at the top of the code."
    "forget about /* this */"

    Continue reading...

Compartilhe esta Página