Python JSON在fi的一部分进行解码

2024-04-25 07:44:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图解码,然后解析一个大约9MB的JSON文件。 但是当我试图解码json文件,使其成为python字典对象时,我得到了一个错误:

'utf8' codec can't decode bytes in position 3161744-3161747: invalid data

我想这可能是因为编码/解码问题,但我不完全确定。我不知道文件的编码方式是什么,因为我是从第三方获取的,不幸的是,我无法显示该文件,因为它包含敏感信息。在

另外,提供JSON文件的人说它是一个有效的JSON文件,并传递JSON lint。 下面是我的代码:

import json

""" JSON Parser """
class parser:
    json_file = None

    """ The JSON File name"""
    def json_object(self, file):
        self.json_file = file

    """ Open up file and parse it """
    def json_encode(self):
        try:
            json_data = open(self.json_file)
            data = json_data.read().decode('utf8')
            result = json.loads(data)
        except Exception as e:
            result = e
        return result

""" Instantiate parser and begin parsing the file"""
p = parser()
p.json_object('file.js')
print p.json_encode()

Tags: and文件selfjsonparserdataobjectdef
1条回答
网友
1楼 · 发布于 2024-04-25 07:44:44

我认为在读入utf-8之前,你不应该解码它。Json对编码应该是透明的,因为Json中可能有一些字符串是utf-8,其他字符串是拉丁语9,等等。请尝试:

json.load(open(self.json_file))

相关问题 更多 >