Python load json file with UTF-8 BOM header - Stack Overflow

时间:2024-07-03 00:04:56

Python load json file with UTF-8 BOM header - Stack Overflow

Since json.load(stream) uses json.loads(stream.read()) under the hood, it won't be that bad to write a small hepler function that lstrips the BOM:

from codecs import BOM_UTF8

def lstrip_bom(str_, bom=BOM_UTF8):if str_.startswith(bom):return str_[len(bom):]else:return str_

json.loads(lstrip_bom(open('sample.json').read()))

In other situations where you need to wrap a stream and fix it somehow you may look at inheriting from codecs.StreamReader.