[lang-ref] ( example_parse_jsonc ) ( python )

def test_example_parse_jsonc():
    import json
    import re
    def remove_jsonc_comment(jsonc_text):
        # Caveat: This is a naive implementation.
        # It assumes comment-like patterns do not appear inside JSON string values.
        text = jsonc_text
        text = re.sub(r'//.*$\n'           , ''      , text, flags = re.MULTILINE)
        text = re.sub(r'/\*.*?\*/'         , ''      , text, flags = re.MULTILINE | re.DOTALL)
        text = re.sub(r',([\s\n]*)(\]|\})' , r'\1\2' , text, flags = re.MULTILINE)
        return text

    jsonc_string = '''\
{
    // name
    "name": "test", /* this is memo */
    "lines": [
      "val1",
      "val2",
      "val3",
//    "val5",
//    "val6",
    ]
}
'''
    expected = {
        "name": "test",
        "lines": ["val1", "val2", "val3"]
    }

    json_string = remove_jsonc_comment(jsonc_string)
    json_object = json.loads(json_string)

    assert json_object == expected