Validate and format JSON files

后端 未结 3 1530
情歌与酒
情歌与酒 2021-02-01 16:04

I have around 2000 JSON files which I\'m trying to run through a Python program. A problem occurs when a JSON file is not in the correct format. (Error: ValueError: No JSO

3条回答
  •  耶瑟儿~
    2021-02-01 16:58

    Yes, there are ways to validate that a JSON file is valid. One way is to use a JSON parsing library that will throw exceptions if the input you provide is not well-formatted.

    try:
       load_json_file(filename)
    except InvalidDataException: # or something
       # oops guess it's not valid
    

    Of course, if you want to fix it, you naturally cannot use a JSON loader since, well, it's not valid JSON in the first place. Unless the library you're using will automatically fix things for you, in which case you probably wouldn't even have this question.

    One way is to load the file manually and tokenize it and attempt to detect errors and try to fix them as you go, but I'm sure there are cases where the error is just not possible to fix automatically and would be better off throwing an error and asking the user to fix their files.

    I have not written a JSON fixer myself so I can't provide any details on how you might go about actually fixing errors.

    However I am not sure whether it would be a good idea to fix all errors, since then you'd have assume your fixes are what the user actually wants. If it's a missing comma or they have an extra trailing comma, then that might be OK, but there may be cases where it is ambiguous what the user wants.

提交回复
热议问题