【问题标题】:Validate and format JSON files验证和格式化 JSON 文件
【发布时间】:2014-06-14 05:27:23
【问题描述】:

我尝试通过 Python 程序运行大约 2000 个 JSON 文件。当 JSON 文件的格式不正确时会出现问题。 (错误:ValueError: No JSON object could be decoded)反过来,我无法将其读入我的程序。

我目前正在做类似以下的事情:

for files in folder:
    with open(files) as f:
        data = json.load(f); # It causes an error at this part

我知道有离线方法可以验证和格式化 JSON 文件,但有没有一种编程方式来检查和格式化这些文件?如果没有,是否有免费/便宜的替代方法来离线修复所有这些文件,即我只是在包含所有 JSON 文件的文件夹上运行程序并根据需要对其进行格式化?


使用@reece 的评论解决:

invalid_json_files = []
read_json_files = []
def parse():
    for files in os.listdir(os.getcwd()):
        with open(files) as json_file:
            try:
                simplejson.load(json_file)
                read_json_files.append(files)
            except ValueError, e:
                print ("JSON object issue: %s") % e
                invalid_json_files.append(files)
    print invalid_json_files, len(read_json_files)

原来我在我的工作目录中保存了一个不是 JSON 格式的文件,这与我从中读取数据的位置相同。感谢您提供有用的建议。

【问题讨论】:

  • 如果您不知道错误的确切位置,您打算如何修复这些文件?
  • 什么格式不好?您意识到您覆盖了每个文件的数据对象,是吗?
  • @frostnational 我的印象是一个程序会检查 JSON 文件中可能出现的一些问题,如果它们发生,它会自动修复这些问题。例如。 {text : "foo"} text2 : "bar" -> 没有逗号分隔两个字典。 @Llopis:是的,我希望程序能够处理每个 JSON 文件。也许格式正确可能会在字典之间缺少一列。

标签: python json


【解决方案1】:

我不清楚如何提供文件夹的路径,所以我想用这个选项提供答案。

path = r'C:\Users\altz7\Desktop\your_folder_name' # use your path
all_files = glob.glob(path + "/*.json")

data_list = []
invalid_json_files = []

for filename in all_files:
    try:
        df = pd.read_json(filename)
        data_list.append(df)
    except ValueError:
        invalid_json_files.append(filename)

print("Files in correct format: {}".format(len(data_list)))
print("Not readable files: {}".format(len(invalid_json_files)))
#df = pd.concat(data_list, axis=0, ignore_index=True) #will create pandas dataframe 
from readable files, if you like

【讨论】:

    【解决方案2】:

    这是一个完整的 python3 示例,供下一个偶然发现此答案的新手 Python 程序员使用。我将 16000 条记录导出为 json 文件。我不得不多次重新启动该过程,因此我需要在开始导入新系统之前验证所有 json 文件确实有效。

    我不是 python 程序员,所以当我尝试上面写的答案时,什么也没发生。好像少了几行代码。下面的示例处理当前文件夹或特定文件夹中的文件。

    verify.py

    import json
    import os
    import sys
    from os.path import isfile,join
    
    # check if a folder name was specified
    if len(sys.argv) > 1:
        folder = sys.argv[1]
    else:
        folder = os.getcwd()
    
    # array to hold invalid and valid files
    invalid_json_files = []
    read_json_files = []
    
    def parse():
        # loop through the folder
        for files in os.listdir(folder):
            # check if the combined path and filename is a file
            if isfile(join(folder,files)):
                # open the file
                with open(join(folder,files)) as json_file:
                    # try reading the json file using the json interpreter
                    try:
                        json.load(json_file)
                        read_json_files.append(files)
                    except ValueError as e:
                        # if the file is not valid, print the error 
                        #  and add the file to the list of invalid files
                        print("JSON object issue: %s" % e)
                        invalid_json_files.append(files)
        print(invalid_json_files)
        print(len(read_json_files))
    parse()
    

    例子:

    python3 verify.py

    python3 verify.py somefolder

    使用 python 3.7.3 测试

    【讨论】:

      【解决方案3】:

      内置的 JSON 模块可以用作验证器:

      import json
      
      def parse(text):
          try:
              return json.loads(text)
          except ValueError as e:
              print('invalid json: %s' % e)
              return None # or: raise
      

      您可以使用以下方法使其与文件一起使用:

      with open(filename) as f:
          return json.load(f)
      

      而不是json.loads,您也可以在错误消息中包含文件名。

      在 Python 3.3.5 上,对于 {test: "foo"},我得到:

      invalid json: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
      

      在 2.7.6 上:

      invalid json: Expecting property name: line 1 column 2 (char 1)
      

      这是因为正确的 json 是 {"test": "foo"}

      在处理无效文件时,最好不要进一步处理它们。您可以构建一个 skipped.txt 文件,列出有错误的文件,以便手动检查和修复它们。

      如果可能,您应该检查生成无效 json 文件的站点/程序,修复该问题,然后重新生成 json 文件。否则,您将继续拥有无效 JSON 的新文件。

      否则,您将需要编写一个自定义 json 解析器来修复常见错误。有了这个,您应该将原始文件置于源代码控制之下(或存档),这样您就可以查看并检查自动化工具修复的差异(作为健全性检查)。模棱两可的情况应该手动解决。

      【讨论】:

        【解决方案4】:

        是的,有一些方法可以验证 JSON 文件是否有效。一种方法是使用 JSON 解析库,如果您提供的输入格式不正确,该库将引发异常。

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

        当然,如果你想修复它,你自然不能使用 JSON 加载器,因为它首先不是有效的 JSON。除非您使用的库会自动为您解决问题,否则您可能甚至不会有这个问题。

        一种方法是手动加载文件并将其标记化,并尝试检测错误并尝试在执行过程中修复它们,但我确信在某些情况下无法自动修复错误并且会更好关闭抛出错误并要求用户修复他们的文件。

        我自己没有编写 JSON 修复程序,因此我无法提供有关您如何实际修复错误的任何详细信息。

        但是我不确定修复所有错误是否是一个好主意,因为那时你会假设你的修复是用户真正想要的。如果它缺少逗号或者他们有一个额外的尾随逗号,那么这可能没问题,但在某些情况下用户想要的内容可能不明确。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-18
          • 2021-10-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多